cin.ignore() function in C++ not working for the whole stream

I am trying to safely input an integer between 1 and 25 but the code I've been told to use does not work properly. That's the code:

*int SafelyInputInteger(int lowerBound, int upperBound)
{
    int intNumber;
    do {
        cout<<"Input a number: "; cin>>intNumber;
        if(cin.fail())
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
            continue;
        }
    } while((intNumber<lowerBound)||(intNumber>upperBound));
    return intNumber;
}
int main()
{
int height;
height=SafelyInputInteger(1,25);
cout<<"Height is: "<<height<<endl;
 return 0;
}*

The error I get is the following: error: 'numeric_limits' was not declared in this scope error: expected primary-expression before '>' token error: no matching function for call to 'max()'

Upvotes: 2

Views: 704

Answers (1)

P.W
P.W

Reputation: 26800

The exact error you mentioned occurs when compiling with GCC and not including <limits> header.

<source>: In function 'int SafelyInputInteger(int, int)':
<source>:16:24: error: 'numeric_limits' was not declared in this scope
                 cin.ignore(numeric_limits<streamsize>::max(),'\n');

                        ^~~~~~~~~~~~~~
<source>:16:49: error: expected primary-expression before '>' token
                 cin.ignore(numeric_limits<streamsize>::max(),'\n');

                                                     ^
<source>:16:56: error: no matching function for call to 'max()'
                 cin.ignore(numeric_limits<streamsize>::max(),'\n');

See live demo here. Compiler version used: GCC 8.2
Including the <limits> header resolves this issue.

Upvotes: 1

Related Questions