C++从istream中读取int,检测溢出

Mat*_*att 5 c++ stream

如果我使用>>运算符读取istream中的整数,并且表示的整数大于INT_MAX,则操作只返回INT_MAX.

我目前正在对INT_MAX进行比较以检测溢出,但如果操作输入"2147483647",则它将返回错误,而实际上没有,结果有效.

示例:http://ideone.com/4bXyGd

#include <iostream>
#include <sstream>
#include <climits>

int main() {
    std::istringstream st("1234567890123"); // Try with 2147483647
    int result;

    st >> result;

    if (result == INT_MAX)
        std::cout << "Overflow!" << std::endl;
    else
        std::cout << result << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是什么意识形态正确的方法?

Dav*_*own 9

对于一般的解析失败(包括数字太大或太小),您只需检查已设置的字符串流的失败位.最简单的方法是:

if (!st) {
    std::cout << "Could not parse number" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在C++ 11之前,没有办法使用此方法专门检查溢出或下溢.但是在C++ 11中,如果解析后的值对于类型来说太大或太小,则除了设置的失败位之外,结果将设置为类型可以容纳的最大值(std::numeric_limits<Type>::max()或std::numeric_limits<Type>::min()).

所以在C++ 11中检查值是否太大或太小你可以这样做:

if (!st) {
    if (result == std::numeric_limits<int>::max()) {
        std::cout << "Overflow!" << std::endl;
    } else if (result == std::numeric_limits<int>::min()) {
        std::cout << "Underflow!" << std::endl;
    } else {
        std::cout << "Some other parse error" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)