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)
If the read fails operator>>
will set the value to zero (cppreference):
If extraction fails, zero is written to value and failbit is set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With