what happens when you cin>> letter to int variable? I tried simple code to add 2 int numbers, first read them, than add them. But when I enter letter, it just fails and prints tons of numbers to screen. But what causes this error? I mean, I expected it to load and use ASCII code of that letter.
I assume you have code like this:
int n;
while (someCondition) {
std::cin >> n;
.....
std::cout << someOutput;
}
When you enter something that cannot be read as an integer, the stream (std::cin) enters a failed state and all following attempts at input fail as long as you don't deal with the input error.
You can test the success of an input operation:
if (!(std::cin >> n)) //failed to read int
and you can restore the stream to a good state and discard unprocessed characters (the input that caused the input failure):
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Another possibility is to accept input into a string variable (which rarely fails) and try to convert the string to int.
This is a very common problem with input and there should be tons of threads about it here and elsewhere.
if you explicitly cast your char to an int, it'll use the ASCII code, else it's not doing the cast by itself to int, so you get the strange results you are getting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With