loop involving "cin.fail()" running multiple times

  c++, cin, input, iostream

I am having trouble with the following code. It is meant to keep asking for a valid input until an integer or double is inputted. It works as intended for characters, however when I input a string of length more than 1, it will run the loop multiple times. For example, the input "hello" with cause "Please enter a valid number" to be printed 5 times. Interestingly "h llo" will only print the sentence 4 times.

int gamenumber;

while(true)
{
    cin >> gamenumber;
    
    if(cin.fail())
    {
        cout << "Please enter a valid number" << endl;
        cin.clear();
        cin.ignore();
        
    } else
        break;

I did manage to fix this issue by replacing "cin.ignore()" with "cin.ignore(1000, ‘n’)".

But regardless, it’s bugging me that I don’t understand why "cin.ignore()" alone doesn’t fix this? Is there a way to fix the above code without using "cin.ignore(1000, ‘n’)"? (This is part of a homework assignment, and we may not be allowed to use "cin.ignore(1000, ‘n’)")

Thank you!

Source: Windows Questions C++

LEAVE A COMMENT