0

I have a simple C++ menu with selectable menu options. If the user types anything other than a valid int, such as a char or double, the program will go into an infinite loop. My code is as follows.

#include <iostream>

using namespace std;

int main()
{
    int selection;
    do  {
        cout << "1) Update inventory" << endl;
        cout << "2) Sell items" << endl;
        cout << "3) List inventory" << endl;
        cout << "4) Quit" << endl;

        cout << "Please select an option: ";
        cin >> selection;
    }
    while (selection != 4);

    return 0;
}

Why do invalid responses cause an infinite loop and how can it be prevented?

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
  • you want to check the validity of the stream, like `if (!cin) { /*handle error*/ }`. See also [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – jaggedSpire Oct 25 '16 at 19:04

1 Answers1

-1

Before the

cin >> selection;

Place these two lines:

cin.clear ();
cin.ignore ();

This will clear the buffer and allow input to be taken.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Tim Palmer
  • 46
  • 8