简体   繁体   中英

C++: Ignoring input after first cin.ignore

Okay, so this is a part of my program which is basically a recurring error message to the user until a valid input is fed. So basically the issue I'm facing is that whenever I enter a number that is invalid (such as 0, 12 or a negative number), nothing will output and the program will await another input, only then will it identify the input as an error or a valid input. This is not a problem when a symbol or alphabet is input. Is there any workaround I can use?

while (Choice1 < 1 || Choice1 > 11) 
{
    if(!(cin >> Choice1), Choice1 < 1 || Choice1 > 11)
    {   
        cin.clear();
        cin.ignore(512, '\n');
        cout << "\n\aError! Please enter a valid input!" << endl;
        cout << "Now please enter the first code: ";
        cin >> Choice1;
    }
}

Perhaps this is what you intended:

#include <iostream>
#include <limits>

int main()
{
    int Choice1{0};

    while (!(std::cin >> Choice1) || Choice1 < 1 || Choice1 > 11) 
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        std::cout << "Error! Please enter a valid input!" << std::endl;
        std::cout << "Now please enter the first code: " << std::endl;
    }

    return 0;
}

You can read here and/or here about the comma operator which I didn't find to belong there as part of the conditional expression . Also, I don't think you really wanted that if en-scoping the while loop . I've made some additional small changes, leaving most of the original structure -- which still could use some work.

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