Easy way to test if input is the correct variable type?

So I am using the cin command to have the user get a number value and place it into an int type variable. The problem is that if the user enters an 'a' for example, the program crashes.

Is there a simple loop I can use that checks the variable type, and just outputs "Invalid entry" if a char is entered and asks for another entry?
You would have to validate the input. This should work as long as you are not keeping a tally and have to clear the buffer (something I am still confused and having issues with).

1
2
3
4
while(!(cin >> your int)
{
     //prompt the user for correct input and loop back
}


Also note that this takes care of your cin input stream all together. If you have

1
2
cin >> your int
while(!(cin >> your int)


you will be prompting the user twice, just use

1
2
cout << //whatever you say to the user
while(!(cin >> your int)
Last edited on
I aught to copy/paste this code into notepad or something:

1
2
3
4
5
6
7
8
9
10
11
int i;
while (!(cin >> i)){  // If the extraction breaks the cin object
 cin.clear();             // Fix it
 cin.ignore(80, '\n)  // Ignore everything else in the buffer (we hope)

 cout << "You messed up, try again";

}


cin.ignore(80, '\n);  // For if the first entry was valid 

@LowestOne, would the cin.clear(); function clear the buffer if a tally is being kept and restart the tally?
You could also read the input into a string, and use a stringstream to try to convert it to an int.

It would be something like
1
2
3
4
5
6
7
8
9
10
int yourInt; // This is what you want the user to input
string input;
getline(cin, input);
istringstream convert;
while (convert.str(in), !(convert >> yourInt))
{
    cout << "Bad input, try again: ";
    getline(cin, input);
    convert.clear(); // Clear the error flag
}
@Long Double Main: wouldn't this ask for two integers the first time around?

Clearing cin would not clear the buffer. I'm not sure if an extraction that breaks cin actually extracts either. I think without the ignore you will still loop forever.
@LowestOne:
I don't think so.
Try it for yourself!
clear() clears the error flag. However, the data that caused the error has not been read, and so you will infinitely get errors. You need to sync() after you clear().
Topic archived. No new replies allowed.