Effects on Input Variable after Failed Input Stream

依然范特西╮ 提交于 2019-12-20 02:32:15

问题


I was working on the following code.

#include <iostream>

int main()
{
  std::cout << "Enter numbers separated by whitespace (use -1 to quit): ";
  int i = 0;
  while (i != -1) {
    std::cin >> i;        
    std::cout << "You entered " << i << '\n';
  }
}

I know that using while (std::cin >> i) would have been better but I don't understand a specific occurrence. If I provide an invalid input, the loop becomes infinite because the Input Stream enters a failbit state. My question is that what happens to the input variable i? In my case, it becomes 0 regardless of the previous value entered. Why does it change to 0 after an invalid input? Is this a predefined behaviour?


回答1:


You get zero because you have a pre-C++11 compiler. Leaving the input value unchanged on failure is new in the latest standard. The old standard required the following:

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set.

(source)

For gcc, you need to pass -std=c++11 to the compiler to use the new behavior.



来源:https://stackoverflow.com/questions/17430495/effects-on-input-variable-after-failed-input-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!