Consider the following 2 code snippets:
Case 1:
#include <iostream>
int main()
{
int i=0;
char c='a';
i=c;
cout << i << endl; //Retuens ASCII value of 'a'
return 0;
}
Case 2:
#include <iostream>
int main()
{
cout << "Enter integer value" << endl;
int i=-1;
cin >> i; //Assume user enters 'a'
cout << i << endl; //prints -1 on screen
return 0;
}
In Case 1, when we use assignment the ASCII equivalent of 'a' is assigned to int i, but in Case 2 int i is -1. Why is the behavior different in both the cases? Is it by design? Is it possible (with standard functions) to input ASCII value using cin when characters are input for integer variables?
// I understand that cin is failing. What I would like to know is: why cin fails when char is entered, if assignment properly assigns ascii value?
When the user enters
'a', the operator implementation tries to convert this to an integer, and fails.In response to the comment (which seems to be the main point of your question):
'a'is not “an ASCII value”. In the C language, it is a character literal.But
cindoesn’t know what a character literal is. As far ascincan tell, the user entered this:cinis not a C++ compiler. It is much simpler, and you might argue much stupider. When you tell it to stream in an integer, it is going to stream in an integer (and only an integer). If that integer happens to correspond to a character in the ASCII table, so be it, but the user must enter it as85.The fact that the stream input operators are “stupid” is actually a good thing, because:
The stream input operators (
>>) aren’t just used for console input. They are also used for file input, which needs to be fast, and secure.