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?
 
     
    