-
Int, Char mix up
Hi I apologise that this has most likely been asked many many times (so obviously if it's anoying you, dont worry about repying :) )
Anyway If I got a while loop where the condition needs an int to end the loop, how can I catch a error if someone enters a character instead, because then I just get a indefinite loop.
For example if I create a variable of type Int Answer
it's looking for a integer but as soon as I put a character I get all sorts of fun things happen, would an If statement be the way past this?
I appreciate your time in answering in advance.
Chris
Fourm Rebel with a cause!
-
cin goes into an error state if that happens, which means it will ignore all further read requests. You can test this state with the fail() or good() methods, or just direct bool conversion:
Code:
if(cin) {
// cin is fine
}
if(!cin) {
// cin is not fine, either in error state or at end of file
}
You can call clear() to reset cin, but you also need to call ignore() to get rid of the invalid characters in the input buffer.
P.S: What's a "fourm rebel"?
-
chars are really just small ints.
use isdigit() to determine whether your char is a digit or not. isdigit is declared in ctype.h.
in your case I'd use a switch() statement. you can also use an else-if to achieve the same test, but if you are wanting to test against several different characters than a switch() might be a better alternative.
-
It is easy to use a while loop to check for the int and prompt the user to try again if it is not a vali integer.
Code:
int value = 0;
// Prompt for input
while (!(std::cin >> value))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Tell the user they typed in bad input here and prompt again.
}
This is simple and works in most every case. One case where it might not work is if you want it to error out when the user types extra characters within or after the number (e.g. 1234abc or 123r5). To test for that, simply change the while loop to:
Code:
int value = 0;
// Prompt for input
while (!(std::cin >> value) || std::cin.get() != '\n')
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Tell the user they typed in bad input here and prompt again.
}
Note that you have to #include <limits> to use numeric_limits. You can also just use a large number there.
-
Thanks
Thanks Guys, very kind of you!
-
Code:
while (!(std::cin >> value) && std::cin.get() != '\n')
I believe you must use || instead of && here.