c++streamcin

What happens when we store a "char type" value in an "integer type" variable using std::cin?


int i;
std::cin >> i; // i = 'a'

What is the reaction of std::cin when we try to do this?
As we know when the std::cin gets a value, it converts it into ASCII or something other and then stores it in a variable so what is the reaction of std::cin on this?


Solution

  • No it doesn't store the ASCII value of the character you are entering into i. Instead, the stream will put a fail flag for the input stream meaning the reading of integer resulted in a failure. Here is the code to demonstrate that.

    int i;
    cout << cin.fail();     // 0 as cin doesn't failed yet
    cin >> i;               // A char is entered instead of integer
    cout << cin.fail();     // 1 as cin failed to read a character