C++ Read int from istream, detect overflow

前端 未结 2 1988
死守一世寂寞
死守一世寂寞 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:10

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

    boost::lexical_cast is a good library for this. It will throw an exception if the value cannot fit in the target type.

提交回复
热议问题