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

前端 未结 5 1948
北恋
北恋 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:05

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

    #include 
    #include 
    // ...
    std::cin.ignore(std::numeric_limits::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 
    #include 
    
    int main()
    {
        int move2, size(3);
        while (!(std::cin >> move2) || move2 < 1 || size < move2) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits::max(), '\n');
            std::cout << "invalid input ignored; please enter a valid move\n";
        }
        std::cout << "move2=" << move2 << '\n';
    }
    

提交回复
热议问题