简体   繁体   中英

How do I validate input without exiting my do while loop?

I'm working on a program that prompts the user to select from 3 different options by inputing an integer from 1-3 (4 to quit). I need to write a code that validates that the input is an integer, and reprompts them if it is not an integer. Here's the basic idea of my code (it is too long to post in entirety).

do 
{
cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
}while (first_input!=4)

I then have multiple if statements that execute expressions based on which option the user chooses. I also prompt them to enter other integer values later in the code.

How do I send the user back to the menu, if the user inputs fails to input an integer and instead inputs characters? Constraints: Cannot use continue or break

Thanks in advance.

If you want to go back to the start in case of non-integer input, perhaps something like this would work?

// Insert after "cin >> first_input;"
if (cin.fail()) {
    // Handle non-int value.

    // Clear error flag.
    cin.clear();

    // Empty buffer up to next newline.
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // Complain & restart.
    cout << "Invalid input.  Please try again." << endl;
    continue;
}

What this does is clear the error flag, purge the buffer, and go back to the start. cin.ignore() doesn't explicitly need to be passed std::numeric_limits<std::streamsize>::max() as its first parameter; however, in case of error, I prefer to do so to make sure that the erroneous input is gone. Note that std::numeric_limits is defined in the standard header <limits> , and requires its inclusion.

您正在寻找continue关键字。

do 
{
    cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
    //lets say if user enters value out of range. then want to show menu again.
    if(first_input > 4) {
        cout << "Invalid input "<<endl;
        continue;
    }
    // you can do other stuff here. 
    // ...
}while (first_input!=4)

You can try using goto label.

 do{ label: // your code if(check) goto label; }while(check); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM