I am learning about implicit conversions in C . And i read the following example:
char a;
std::cin>>a; //I can enter an integer like 56 here
std::cout<<a<<std::endl; //for the input 56 it will display 5 because of its ASCII value
I understood the above example by reading about it in different books and posts on SO. For example, if i provide the input J, then the program successfully prints J on the console. Similarly if i provide the input say 56 then the output will be 5 because of its ASCII value.
But then i tried the opposite as shown below:
int a;
std::cin>>a;//if i provide the input as the character J then why is the output 0 instead of the corresponding code point of `J`
std::cout<<a<<std::endl;
For the above snippet, if i provide the input 56 then the output is correctly printed as 56. But if i provide the input as J then the output is 0.
So my question is in the above 2nd snippet why the code point corresponding to the character J is not printed and instead we get 0 printed on the console. I mean, a is an integer variable so it is able to store the code point corresponding to the character J and then when we do cout<<a; we should be getting that code point as the output instead of 0. What is happening here. Is this related to implicit conversion like a char can be promoted to an int or something else.
CodePudding user response:
When istream operator<< expects something but gets something else, its failbit is set and in this state, the stream will not do anything.
So if there is a chain, it is stopped when a wrong input is met.
About handling this here.
But something else is also happening.
Since C 11, if extraction fails, zero is written to its value.
int a; // default-initializing fundamental type (no init / garbage value)
std::cin >> a;
If a char is encountered, a will become 0.
And also for integers, if the entered value is more or less than the type can hold, failbit is set and it will become std::numeric_limits<T>::max/min() or max() if T is unsigned.
CodePudding user response:
The << operator works different depending on what is on the right hand side. In the first example it reads the char ‘5’ with a ASCII value of 53 and throws the ‘6’ away. In the second case it reads the int fifty-six. When you enter “J” that’s not an int, so trying to read an Int gets a result of 0.
And the >> operator does the same thing: When you output ‘5’ it’s written, it is written as a char, and the int 56 is written as an Int.
