Converting string to unsigned int returns the wrong result

You should instead use std::strtoul, found in <cstdlib>, which is designed for unsigned numbers, has a larger range, and reports errors better.

If you want to use std::string for input and exceptions for error handling, use std::stoul. A short, highly efficient implementation would be as follows:

#include <string>
#include <stdexcept>
inline unsigned int stoui(const std::string& s)
{
    unsigned long lresult = stoul(s, 0, 10);
    unsigned int result = lresult;
    if (result != lresult) throw std::out_of_range();
    return result;
}

This will be much faster than istringstream, culture-invariant (so no unexpected changes to behavior when run in an unusual locale), completely portable, and using the third argument, you can support different numeric bases or even perform detection of 0x and 0 prefixes.

But unsigned int isn’t necessarily big enough to hold your value, so use unsigned long, and then you won’t need the above wrapper.

Leave a Comment