Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

cin

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.

like image 316
RickSanch3z Avatar asked Aug 16 '18 06:08

RickSanch3z


2 Answers

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)

like image 113
songyuanyao Avatar answered Oct 18 '22 01:10

songyuanyao


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

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

like image 25
vitaut Avatar answered Oct 18 '22 00:10

vitaut