keyboard error handling
I am writing a simple program for school that lets a user input a number and it tells them if they are too high or too low. But I going to be tested for all situations, including the user entering an invalid key. I was wondering if there was any way that you could handle the user pressing a letter on the keyboard. I'm new to this so any help would be greatly appreciated. Thank you.
There are several different ways. One is to use the fail(), clear(), ignore() members of the istream class. Another is to accept input into a string, validate the string, then convert the string to desired type. There may be others as well.
I would opt for the latter option. It could be done somewhat like this:
bool ok = true;
for(int i = 0; i < input.size(); ++i)
if((input[i] - '0') > 9)
ok = false;
cout << "Failed";
// other code...
I would like to recommend the isdigit( ) function of the <cctype> library. It is a boolean function that will return true if the argument is a number.
Well I thought it wasn't standard..
isdigit() returns a non-zero value when the input parameter is a numberic digit, not true. But the point is still the same. And it is standard.
to tilex... would i put that as just its own separate block of code in int main() ?
You should be able to figure that on your own, I've already said more than I should have. Study the code and then when you know what it does, you'll know where it goes.