How to catch invalid input in c++?

后端 未结 3 1981
半阙折子戏
半阙折子戏 2020-12-11 23:33

I am a (somewhat) experienced python programmer trying to migrate to C++. I want to be able to catch invalid user input. For instance, if a variable requires an integer, and

3条回答
  •  星月不相逢
    2020-12-12 00:17

    Streams don't throw exceptions by default (they can be configured to do so).

    The usual code to read an int is:

    int a;
    if (std::cin >> a) {
        # OK
    } else {
        # error
    }
    

    But do be sure that you know what >> actually does here. Specifically, newcomers to C++ are sometimes surprised that it doesn't necessarily read a whole line. So, if you want to validate a whole line of input, or for that matter if you want to retry on failure then you need more code.

提交回复
热议问题