10

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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
RickSanch3z
  • 129
  • 7
  • The input that `std::cin` reads is a stream of text. Beyond that, it does not have a type. The extractor (`operator>>`) **converts** that text into a value of the appropriate type if it can. – Pete Becker Aug 16 '18 at 12:53

2 Answers2

18

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)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    If no characters could be read then the value is unchanged; the setting 0 only happens on conversion failure – M.M Aug 16 '18 at 09:12
  • 2
    Just for information: I've used `std::cin.fail()` to check if there a *failbit* set. – RickSanch3z Aug 16 '18 at 09:39
4

If the read fails operator>> will set the value to zero (cppreference):

If extraction fails, zero is written to value and failbit is set.

vitaut
  • 49,672
  • 25
  • 199
  • 336