Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin.ignore(numeric_limits<streamsize>::max(), '\n'); max() not recognize it

Tags:

c++

I'm taking an intro to C++, and I'm using VStudio 2013 on Win7. I try to avoid the wrong data input from my menus, and it's working in all of them except this one.

    cout << "Please choose your second number" << endl;
    cin >> move2;

    if (move2 < 1 || move2 > size)
    {
        cout << "That's not a valid move" << endl;
        Sleep(2000);
        cin.sync();
        cin.clear();
    }

the only difference is that in the condition for move > a variable (size) not a number. When I enter a char it goes back to the question asking for another input, but if I enter a word, it breaks!

I try to use cin.ignore(numeric_limits<streamsize>::max(), '\n'); but the compiler highlights max() and it says "expecting identifier".

It maybe easy for all of you good programmers, but I don't know how to fix it. Can anybody help me?

like image 807
user3078454 Avatar asked Dec 07 '13 20:12

user3078454


2 Answers

This is because in Visual Studio when you use the windows includes it will define a macro max(). If you hover over the max() in your example you should receive an intellisense warning. You can solve this problem by undefining max after all your includes and before any code.

#undef max
like image 120
loop Avatar answered Nov 11 '22 22:11

loop


To use std::numeric_limits<T> you'll need to include <limits>. Further, the type passed to it need to be known and actually the type std::streamsize, i.e., I would use it as

#include <iostream>
#include <limits>
// ...
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Also, you should probably make sure that your attempt to read something was actually successful and, if it was not, first clear() the stream's state. Here is a complete program (it certainly compiles and runs with gcc and clang):

#include <iostream>
#include <limits>

int main()
{
    int move2, size(3);
    while (!(std::cin >> move2) || move2 < 1 || size < move2) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "invalid input ignored; please enter a valid move\n";
    }
    std::cout << "move2=" << move2 << '\n';
}
like image 8
Dietmar Kühl Avatar answered Nov 11 '22 22:11

Dietmar Kühl