vmishel
vmishel

Reputation: 145

Stop cin from continuing to take in inputs

I'm making a small program that is meant to ask the user for a number that is between a specific range and it needs to make sure that it is, in fact, an actual number.

int main()
{
    double initEstimate = 99;
    int tries = 0;

    do
    {
        tries++;
        cout<<"enter value: ";
        cin>>initEstimate;

        if( initEstimate < -10 || initEstimate > 10 )
        {
            cout<<"value not in range"<<endl;
            initEstimate = 99;
        }

        else if( cin.fail() )
        {
            cout<<"not a number"<<endl;
            cin.ignore();
            cin.clear();
            initEstimate = 99;
        }

        if(tries == 3)
        {
            cerr<<"error: too many tries"<<endl;
            return 1;
        }

    }while(initEstimate == 99);

    cout<<"\n\nsuccess"<<endl;
    return 0;
}

Everything works perfectly when testing if the input is in range, however, I run into a problem when it tests if the input is a number and not another character. If I enter, for example, "a" in console, the program blasts through all of the tries immediately and outputs the "too many tries error". I've looked far and wide for a solution to this online but couldn't find anyone having a problem quite like mine. Help a brother out :)

Upvotes: 3

Views: 1581

Answers (2)

L. F.
L. F.

Reputation: 20579

When std::cin is instructed to read in numbers but encounters nonsense input like "abakjdb", it sets failbit to true, and refuses any more input. If you std::cin.clear(), then the failbit, etc. are cleared (i.e. set to false) and further input is possible.

Consult this cppreference page for more about how C++ input streams work. In particular, std::cin is of type std::istream, which is defined to be std::basic_istream<char, std::char_traits<char> >.

Upvotes: 1

vmishel
vmishel

Reputation: 145

Ok, it turns out I simply had to put the cin.clear() statement before the cin.ignore() statement. I don't know why this is the case so if someone could explain it I would be grateful.

Upvotes: 1

Related Questions