Effects on Input Variable after Failed Input Strea

2020-04-10 05:44发布

问题:

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.