C++ character to int

前端 未结 5 1700
梦谈多话
梦谈多话 2020-12-11 16:36

what happens when you cin>> letter to int variable? I tried simple code to add 2 int numbers, first read them, than add them. But when I enter letter, it just fails and prin

5条回答
  •  独厮守ぢ
    2020-12-11 17:01

    I assume you have code like this:

    int n;
    while (someCondition) {
        std::cin >> n;
        .....
        std::cout << someOutput;
    }
    

    When you enter something that cannot be read as an integer, the stream (std::cin) enters a failed state and all following attempts at input fail as long as you don't deal with the input error.

    You can test the success of an input operation:

    if (!(std::cin >> n)) //failed to read int
    

    and you can restore the stream to a good state and discard unprocessed characters (the input that caused the input failure):

    std::cin.clear();
    std::cin.ignore(std::numeric_limits::max(), '\n');
    

    Another possibility is to accept input into a string variable (which rarely fails) and try to convert the string to int.

    This is a very common problem with input and there should be tons of threads about it here and elsewhere.

提交回复
热议问题