C++ Read int from istream, detect overflow

前端 未结 2 1990
死守一世寂寞
死守一世寂寞 2021-01-18 14:45

If I read an integer from a istream using the >> operator, and the represented integer larger than INT_MAX then the operation just returns INT_MAX.

I am currently do

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 15:26

    For general parsing failures (including the number being too large or too small) you can simply check the fail bit of the stringstream has been set. The easiest way to do this is:

    if (!st) {
        std::cout << "Could not parse number" << std::endl;
    }
    

    Before C++11 there was no way to check specifically for overflow or underflow using this method. However in C++11 if the parsed value would be too large or too small small for the type, the result will be set to the largest value the type can hold (std::numeric_limits::max() or std::numeric_limits::min()), in addition to the fail bit being set.

    So in C++11 to check if the value was too large or small you can do:

    if (!st) {
        if (result == std::numeric_limits::max()) {
            std::cout << "Overflow!" << std::endl;
        } else if (result == std::numeric_limits::min()) {
            std::cout << "Underflow!" << std::endl;
        } else {
            std::cout << "Some other parse error" << std::endl;
        }
    }
    

提交回复
热议问题