1

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' ) ; 
}
3
  • 2
    In short: No. If you want to verify the full input you need to read a full line as a string and then attempt to convert it to a number with validation. The std::getline and std::stoi functions can be used for that. Commented Apr 28, 2020 at 23:46
  • You don't need to read whole lines, just whole words. You can still use cin >> ... for that, but you will have to read into an intermediate string first and then convert that into an int for ID, and perform error handling of that conversion instead of (or in addition to) >>. Commented Apr 29, 2020 at 2:27
  • 1
    On a side note, don't hard-code the count for cin.ignore(), use std::numeric_limits<std::streamsize>::max() instead. Commented Apr 29, 2020 at 2:29

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.