Does “cin” reset variable to some default value if input type differs from destination type? [duplicate]

  • A+

This question already has an answer here:

I have an issue with behavior of "cin" (I do not understand). My IDE is Netbeans under Windows OS (with Cygwin).

Here's a code example:

int main() {     int temp = -1;     std::cin >> temp;    // here user enters string of characters (string) or a single character      if (temp == 0)         std::cout << "temp = " << temp << "./n";     if (temp == -1)         std::cout << "temp = " << temp << "./n";      return 0; } 

This code shows message temp = 0 if I enter some sort of a character/string of characters. It's like there is conversion of char to int and conversion always ending by value 0.

Thank you if you can explain this behavior.


This is expected behavior of std::basic_istream::operator>>; since C++11 if extraction fails, the variable will be set to 0. Before C++11, the variable won't be modified then its original value remains.

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until C++11)

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. (since C++11)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: