Why is it that while using "cin" when we input a character into an integer value, the program malfunctions and executes all the statements, overwriting various switches/checks.
I mean while during compilation if we declare an integer variable and assign it a character value, it stores the ASCII equivalent of that character, but when on runtime we try to input a character into an integer, the program exhibits an odd behavior.
Compile time case:
1 2 3
int a = 0;
a = 'A';
cout << a ; //It displays 65.
Runtime case:
1 2 3
int a = 0;
cin >> a; //Input the character 'A'
cout << a ; //It still displays 0 because it didn't store 'A' in variable at all.
Surely it has something to do with the behavior of the stream, can anyone explain it to me in detail please? Thanks in advance.
So what if you input the character '8'? Should a contain the ASCII value for '8' which is 56 or should it contain the value 8?
Often when you have an int you actually want an integer and not a letter. It's useful that the operation fails so you can handle the failure.
1 2 3 4 5 6 7 8 9
int a = 0;
if (cin >> a)
{
cout << "You have entered the integer value " << a << "." << endl;
}
else
{
cout << "You have failed to enter an integer value!" << endl;
}
If you want to read characters you can use a char variable instead.
cin and operator>> has been designed in way to make it useful, general, safe, etc. If you have an int it is assumed you want to read an integer. If you have a char it is assumed you want to read a character. If you have a string it is assumed you want to read a string.
1 2
int a = 0;
a = 'A';
This on the other hand is just a matter of how conversion from different integer types happens. It is perfectly safe to convert a char to an int and this is done implicit in this case.
'A' is of type char. char is a signed integer type just like int. int is a bit bigger and can hold a larger range of values than char.
When you print a char you get character representation and not the ASCII value. This is often convenient because char is often used to represent characters. It is not so convenient if you are not actually using it as a character. It's not optimal but the work around is easy. All you have to do is cast the char to an int before you print it.
> I am not satisfied with the thing you pointed out.
> Why doesn't it behave in a same manner ...
The behaviour that you are seeing is the default behaviour - the behaviour that most C++ programmers would be comfortable with.
You can make the behaviour to be what you want it to be. Write a custom num_get facet, and make the stream imbue a locale containing your facet. http://en.cppreference.com/w/cpp/locale/num_get