-
Input stream
Hey everyone, how do I make it so when a user enters a string or character when the program is waiting for an integer the program doesn't flip out? I currently have something like:
Code:
while (n!=-1)
{
cin>>n;
}
but the program crashes when a letter or string is entered.
-
-
-
If cin cannot translate what it finds into the appropriate variable, it enters a fail state. You can check for this. Here is some example code:
Code:
#include <iostream>
#define expletive "moron"
using namespace std;
int main () {
int n;
bool nisgood = false;
while (!nisgood) {
cin >> n;
if (cin.fail()) {
cout << "That was supposed to be a NUMBER, " << expletive << ", now try again";
//fflush(stdin); // Heh just kidding
while (getchar() != '\n') {}
cin.clear();
} else nisgood = true;
}
return 0;
}
You can of course make this more elegant by tidying the error checking method into a tighter loop.
-
forgot quotes around moron :D
-
D'oh.
It wasn't "moron" when I typed it. Thats the beauty of macros...