Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ character to int

Tags:

c++

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.

like image 789
Vit Avatar asked Mar 09 '10 09:03

Vit


2 Answers

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.

like image 54
visitor Avatar answered Sep 22 '22 07:09

visitor


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.

like image 44
Tony The Lion Avatar answered Sep 22 '22 07:09

Tony The Lion