Invalid Input leads to Infinite Loop

Hi,

I've a simple menu on my program, and it prompts for an int value.

If a letter or string is entered, the program goes into an infinite loop.

I was looking for a way to guard against invalid input. After some searching I found the following code:

1
2
3
4
5
 if (!(cin >> input)) {
   cout << "Invalid!";
   cin.clear();
   cin.ignore(1000, '\n')
}


However, when I get back to the main menu now, after inputting a valid int, nothing happens.

Can someone help me out?
Isn't the return caracter '\r'? Try it out.
Neither seems to be working. You're right though, '\r' is a carriage return, while '\n' is a newline.
Show more code, then.
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
int
menu()
{
    int choice;

    cout << " **** MENU **** " << endl;
    cout << "[1] Option 1" << endl;
    cout << "[2] Option 2." << endl;
    cout << "[3] Exit the program.\n\n" << endl;
    cout << "NOTE: *** Use CTRL + C to exit the program in case of error. ***\n\n" << endl;
    cout << "Choose an option:" << endl;
    
    if (!(cin >> choice)) {
      cout << "ERROR";
      cin.clear();
      cin.ignore();
   } else {
        cin >> choice;
        cin.ignore();
    }

    cout << "\n\n";

    return (choice);
}


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
int
menu()
{
    int choice;

    cout << " **** MENU **** " << endl;
    cout << "[1] Option 1" << endl;
    cout << "[2] Option 2." << endl;
    cout << "[3] Exit the program.\n\n" << endl;
    cout << "NOTE: *** Use CTRL + C to exit the program in case of error. ***\n\n" << endl;
    cout << "Choose an option:" << endl;
    
    if (!(cin >> choice)) {
      cout << "ERROR";
      cin.clear();
      cin.ignore();
   } else {
        cin >> choice;
        cin.ignore();
    }

    cout << "\n\n";

    return (choice);
}



There is no loop in this code, so I guess you are experiencing a freeze instead? If you debug and run the code line by line, where does the program get stuck?

Also the else{} block @ line 17 is not necessary.

I would write:

1
2
3
4
5
6
7
8
while (true)
    if (!cin >> choice)
    {
        cout << " ERROR:  Please try again." << endl;
        cin.clear();
        cin.ignore();
    }
    else break;
Last edited on
Topic archived. No new replies allowed.