Is there a simple way of catching bad input for integers? Say if someone enters a character instead?
Printable View
Is there a simple way of catching bad input for integers? Say if someone enters a character instead?
One way (how i do it) is to come up with something like this:
good luck, if it doesn't work....consult an expertCode:int main() {
//make an int array
//if you're reading INTEGER from cin(), you must give it a size first
//to avoid compiling errors
int INTEGER[1000];
//set up boolean variable for use in while loop, set it to false (0)
bool isOK="0";
while (isOK=="0") {
cout<<"enter integer"<<endl;
cin>>INTEGER;
//now that you have it, test it for letters
//cycle through entire alphabet based on this example
if (INTEGER[0]=='a'||'b'||'c') {
//since it got to here, there were letters in the variable so set
//bool to false, which will make the loop go again and ask for
//INTEGER until it checks out
isOK="0";
}
//repeat for INTEGER[1], etc., up to a reasonable number,
//obviously you don't want to go to 1000 (p.s. 1000 was just
//an example size
//now if you checked for all the parts of the array, time to allow
//it to break out if there were no letters
else{
isOK="1";
}
//that will break the loop if everything was fine, repeat just as
//the last set of checks
//P.S. don't forget to place the else right after the } in each
//if statement, otherwise it won't compile correctly
}
[edit]changed my mind, added else statements to code to avoid too much typing, sorry i didn't think of it first, it's been a long day[/edit]
The way i've been looking at is something similar to this:
Was just wondering if there was a simpler way....Code:float af;
int a;
cin >> af;
a = (int) af;
if (cin.fail() || (af-(float)a != 0))
throw CWrongDataType();
like i implied, im not an expert, im not even all the way through the book i bought ;) ...anyhow, that looked good and would worka heck of a lot better than what i proposed, use that...