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

前端 未结 5 1940
北恋
北恋 2020-12-13 20:44

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.

<
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 21:18

    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 like this (only tested on Windows/Visual Studio 2019):

      // stuff ...
    
    #pragma push_macro("max")
    #undef max
      std::cin.ignore(std::numeric_limits::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::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::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.

提交回复
热议问题