punypaw
punypaw

Reputation: 135

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

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!

Upvotes: 0

Views: 578

Answers (1)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

You need use ignore with the overloaded one, see this anser here.

Or you can just need to run getline to drain the contents, but this way is slower and unnecessary.

#include <iostream>
#include <string>
 
int main()
{
    double n;
    while( std::cout << "Please, enter a number\n"
           && ! (std::cin >> n) )
    {
        std::cin.clear();
        std::string line;
        std::getline(std::cin, line);
        std::cout << "I am sorry, but '" << line << "' is not a number\n";
    }
    std::cout << "Thank you for entering the number " << n << '\n';
}

Upvotes: 1

Related Questions