How to safely read an unsigned int from a stream?

c++, iostream

Solution

You can read into a variable of a signed type that can handle the entire range first and test if it is negative or beyond the maximum of your target type. If your unsigned values may not fit into the largest signed type available, you'll have to do parsing using something other than iostreams.

Problem

In the following program ``` #include <iostream> #include <sstream> int main() { std::istringstream iss("-89"); std::cout << static_cast<bool>(iss) << iss.good() << iss.fail() << iss.bad() << iss.eof() << '\n'; unsigned int u; iss >> u; std::cout << static_cast<bool>(iss) << iss.good() << iss.fail() << iss.bad() << iss.eof() << '\n'; return 0; } ``` the streams lib reads a signed value into an `unsigned int` without even a hiccup, silently producing a wrong result: ``` 11000 10001 ``` We need to be able to catch those runtime type mismatch errors. If we hadn't just caught this in a simulation, this could have blown up very expensive hardware. How can we safely read an unsigned value from a stream?

Original source

Related problems