Display error message if invalid user input

Hello everyone, so I'm writting a memory matching game. and I'm working on the main menu, there is this part where I want to reprint the menu in case the user inputs an invalid character. Notice the options are integers and when the user inputs integers it works fine, but when the use inputs characters the program will freak out and stop working. How can I make the message still reprint normally without freaking out in case the use inputs a character? I tried using
cin.fail()
but it didn't help at all...This is for my programming class and I'm sure my professor will make me test that when I present next week. Thank you very much for your help! :)

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
  		cout << "Please choose your grid: " << endl << endl;
		cout << "1. 4 x 4 grid (Easy)" << endl;
		cout << "2. 6 x 6 grid (Medium)" << endl;
		cout << "3. 8 x 8 grid (Hard)" << endl << endl;

		cin >> grid;

		if (grid == 1)
		{
			return 16;
		}

		else if (grid == 2)
		{
			return 32;
		}

		else if (grid == 3)
		{
			return 64;
		}

		else
		{
			do{
				system("CLS");
				cout << "Please choose your grid: " << endl << endl;
				cout << "1. 4 x 4 grid (Easy)" << endl;
				cout << "2. 6 x 6 grid (Medium)" << endl;
				cout << "3. 8 x 8 grid (Hard)" << endl << endl;
				cout << "Not a correct response, please try again." << endl;
				cin >> grid;
			} while (grid != 1 && grid != 2 && grid != 3 && grid != 0 || cin.fail());
		}
So here's why your program is "freaking out":

if cin encounters an invalid input it won't extract it from the input buffer. It just leaves it there. So when you go into your do-while loop and get to cin >> grid it reads the invalid value that was extracted earlier... and off you go into an infinite loop.

To fix it, you should use a combination of cin.clear() and cin.ignore() to skip over the bad input. I took it a step further and compacted some of your code so you only have to write out your print code once:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int grid;
bool firstRun = true;
    
do
{
    cout << "Please choose your grid: " << endl << endl;
    cout << "1. 4 x 4 grid (Easy)" << endl;
    cout << "2. 6 x 6 grid (Medium)" << endl;
    cout << "3. 8 x 8 grid (Hard)" << endl << endl;

    if (!firstRun)
    {
        system("CLS");
        cout << "Not a correct response, please try again." << endl;
        cin.clear();
        cin.ignore(INT_MAX, '\n');
    }
    firstRun = false;
} while (!(cin >> grid));
Last edited on
Topic archived. No new replies allowed.