简体   繁体   中英

C++ cin Input Validation in a While Loop

My code is mostly working except for one minor issue. While it should only accept ints, it also accepts user input that start with an int, such as 6abc for example. I saw a fix for this here , but it changed the input type to string and added a lot more lines of code. I'm wondering if there's an easier way to fix this:

int ID;
cout << "Student ID: ";
// error check for integer IDs
while( !( cin >> ID )) {
    cout << "Must input an integer ID." << endl ;
    cin.clear() ; 
    cin.ignore( 123, '\n' ) ; 
}

In a word - no.

But what you can do is instead read a whole word into a std::string first, and then convert that entire word into an int , checking for errors in that conversion, eg:

int ID;
string input;

do
{
    cout << "Student ID: ";
    if (!(cin >> input))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    else
    {
        size_t pos = 0;
        try
        {
            ID = stoi(input, &pos);
            if (pos == input.size())
                break;
        }
        catch (const std::exception &) {}
    }
    cout << "Must input an integer ID." << endl;
}
while (true);

Live Demo

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