3

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 :)

vmishel
  • 145
  • 8
  • Possible duplicate of [How to use cin.fail() in c++ properly](https://stackoverflow.com/questions/33284483/how-to-use-cin-fail-in-c-properly) – Robert Andrzejuk Jan 31 '19 at 10:42

2 Answers2

1

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.

vmishel
  • 145
  • 8
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/22081093) – NelsonGon Jan 31 '19 at 11:14
  • 2
    @NelsonGon in case you did not notice, this was me answering to my own question, so yes, this does in fact provide an answer to the question. – vmishel Jan 31 '19 at 11:44
  • I see, will take more notice next time. My bad! – NelsonGon Jan 31 '19 at 11:45
1

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> >.

L. F.
  • 19,445
  • 8
  • 48
  • 82