Input stream unreactive

Hi !

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 


Original Version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
istream& operator>>(istream& is, Point& p) {
    int a, b;
    is >> a >> b; // simply being leaped over the second time
    if (!is) return is;
    p = Point(a, b);
    return is;
}

void prompt_user_for_input() {
    vector<Point> points;
    Point p;
    int i = 0;
    cout << "Enter point[a b]:\n";
    while (i < 7) {
        if (cin >> p) { //good read
            points.push_back(p);
            i++;
            cout << "Enter point[a b]:\n";
        }
    }
}

void f() {
    prompt_user_for_input();
}

int main() {
    try {
        f();
        keep_window_open();
        return 0;
    } catch (exception& e) {
        cerr << e.what() << "\n";
        keep_window_open();
        return 1;
    } catch (...) {
        cerr << "Oops... unknown exception\n";
        keep_window_open();
        return 2;
    }

}
Last edited on
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";
    }
}
Topic archived. No new replies allowed.