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

Viewed 36192

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?

5 Answers

Code that Limits Potential Side Effects

In my testing, #undef max does not seem to need to be done before any #includes.

You might want to limit potential side effects in general by first pushing the max macro, then undefining it, then popping it off after using max from <limits.h> like this (only tested on Windows/Visual Studio 2019):

  // stuff ...

#pragma push_macro("max")
#undef max
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
#pragma pop_macro("max")

  // more stuff ...

See the Microsoft Docs: push_macro and pop_macro

Put it in a function to make it DRY:

void CinIgnore() {

#pragma push_macro("max")
#undef max
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
#pragma pop_macro("max")

}

Add std::cin.clear to make a CinReset function:

void CinReset() {

  std::cin.clear();

#pragma push_macro("max")
#undef max
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
#pragma pop_macro("max")

}

Additional information: this cppreference.com article on ignorehas a good example of how to use clear and ignore, along with state flags, effectively, but does not have the necessary fix for Windows/Visual Studio noted above.

NOTE: The above, though standard, does not work well with the user interactively inputting EOF (ctrl-z - Windows using Visual Studio). I have written a IStreamUtils class that includes a Reset method that is more robust. I will add a link to an article about that here later.

Related