C ++ Reading int from istream, overflow detection

If I read an integer from istream using the → operator, and the represented integer is greater than INT_MAX, then the operation simply returns INT_MAX.

I am currently doing a comparison with INT_MAX to detect overflow, but if the operation is entered "2147483647", then it will return an error if it really wasn’t, and the result is valid.

Example: 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; } 

What is the ideologically correct way to do this?

+4
source share
2 answers

For common parsing crashes (including too many or too many), you can simply check the bad bit of the string string to specify. The easiest way to do this:

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

Before C ++ 11 could not verify the specifics for overflow or overflow using this method. However, in C ++ 11, if the parsed value is too large or too small for the type, the result will be set to the largest value that the type can hold ( std::numeric_limits<Type>::max() or std::numeric_limits<Type>::min() ), in addition to the bit error.

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

 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; } } 
+9
source

The best way to do this is to read the value as a string and then convert it to an integer. During the conversion, you can catch whether the value fits within the range of the type you are converting into.

boost::lexical_cast is a good library for this. It throws an exception if the value cannot be placed in the target type.

+1
source

Source: https://habr.com/ru/post/1486308/


All Articles