I'm having trouble dealing with illegal user input (string/character instead of int)
I'm reading integer values into an input stream (cin). If the user enters a string/character, like "a" or "b" instead of a number, the read instruction gets simply leaped over from that point on. I guess it's because EOF is set.
I do not think that it has anything to do with the overloaded >> operator. I can simplify the code and get the same result. It even happens if I just read an integer into cin and input the string "a" (or character, if you will) instead of an int.
Simple version
1 2 3
int a,b;
cin >> a >> b;
cin >> a >> b; // simply being leaped over
I think I solved it. This example was from the Stoustrup book "Programming principles and practice Using C++" and he supplied another function which solves this problem (skip_to_int).
With these changes it seems to work
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void skip_to_int() {
if (cin.fail()) { // we found something that wasn't an integer
cin.clear(); //we'd like to look at the characters
char ch;
while (cin>>ch) { // throw away non-digits
cout << "Throw away\n";
if (isdigit(ch)) {
cin.unget(); // put the digit back,
// so that we can read the number
return;
}
}
}
error ("no input"); // eof or bad: give up
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void prompt_user_for_input() {
vector<Point> points;
Point p;
int i = 0;
cout << "Enter point[a b]:\n";
while (true) {
if (cin >> p) { //good read
points.push_back(p);
i++;
} else {
skip_to_int();
}
if (i==7) break;
cout << "Enter point[a b]:\n";
}
}