message error when non no. used

Sep 11, 2010 at 9:40am
I had this posted on the end of one of my other topics, but it was out of place.
in my quiz, if the user enters anything but a number, the message [Please type 1, 2, or 3] loops forever:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
cout << "  Q1\n"; // Midgar
{
	cout << "Where Does FFVII take place?\n";
	cout << " 1: Spira\n 2: Midgar\n 3: Sydney\n";

	while(q1<1 || q1>3)
	{
		cin >> q1;
		if(q1<1 || q1>3) cout << "Please type 1, 2, or 3\n";
	}	
	if(q1 == 2) 
	{
		cout << "CORRECT!!!";
		points++;
	}
	else cout << "WRONG!!!";
}	
cout << "\n\n";


not allowed to say help:
ASSISTANCE!!!
Sep 11, 2010 at 11:20am
operator >> has several overloads. One of them is >> (int). This overload extracts an integer from input stream and stops at first non numeral char. When no numbers are in the stream fail flag is set. To be able to try again, you have to clear the fail flag and empty the stream. example:
1
2
3
4
5
6
7
8
9
10
11
int q;
while(true){
    if(cin>>q){//if input was successful...
        if(q>0 && q < 4) break;
        else cout << "1 2 or 3!\n";
    }else{//if input failed..
        cin.clear();//clear flags and
        cin.ignore(numeric_limits<streamsize>::max(), '\n');//empty stream.
        cout << "that's not a number!\n";
    }
}

note: to use numeric_limits you have to include <limits>
edited typo.
Last edited on Sep 12, 2010 at 2:16pm
Sep 12, 2010 at 12:00pm
Thank you so much!! it finally WORKS!!!
note (line 8):
cin.ignore(numeic_limits<streamsize>::max(), '\n');//empty stream.
Topic archived. No new replies allowed.