Validating input

2019-08-08 10:31发布

cin >> menuChoice;

while (!(cin >> menuChoice))
 {
   cout << "invalid selection, please enter a number from the menu  1" << endl;
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
 }

I want to 'catch' a string so that the programme doesn't crash or go into a continuous loop so I entered the above while loop. Looks good. That is until I entered 0 into menu choice - the !(cin >> menuChoice) gets called even though it is valid input (I'll use another loop to ensure it is within range but as long as it's an int it should be fine, that's what I thought.

I even tried a

if (menuChoice == 0)
   menuchoice = 6;

just before the while loop but to no avail.

Any assistance?

2条回答
甜甜的少女心
2楼-- · 2019-08-08 11:33

turns out it is just

 cin>> menuChoice;

 while (!cin)
  {
   cout << "invalid selection, please enter a number from the menu  1" << endl;
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   cin>> menuChoice;
  }

that is needed (as well as the rest of the code etc)

查看更多
趁早两清
3楼-- · 2019-08-08 11:37

I'm looking to keep the menu and the validation part separate (at the moment its functions but I'll be changing them in the future to classes).

The validation part goes:

while (!(cin >> menuChoice))
{
   cout << "invalid selection, please enter a number from the menu  1" << endl;
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

while (menuChoice < 1 || menuChoice > 4)
{
    cout << "invalid selection, please enter a number from the menu  2" << endl;
    cin >> menuChoice;  //here is where there is a problem

    while (!(cin >> menuChoice))
    {
        cout << "invalid selection, please enter a number from the menu 3" << endl;
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

}

while loop 1 - catches any initial string input while loop 2 - ensures correct range while loop 3 - catches any string input the user may enter a second time

查看更多
登录 后发表回答