C/C++ Arena

Step 5 of 6

Strict number parsing with from_chars

std::stoi throws exceptions and silently ignores trailing junk (stoi("12abc") is 12). atoi can't report errors at all. For parsing untrusted input, <charconv> has std::from_chars: no exceptions, no locale, no allocation, and precise error reporting:

int v;
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), v);
if (ec == std::errc::invalid_argument)     { /* no number at all */ }
if (ec == std::errc::result_out_of_range)  { /* too big for int */ }
if (ptr != s.data() + s.size())            { /* junk after the number */ }

It's also the fastest parser in the standard library, which matters when loading big files.

Your turn: write std::optional<int> to_int(std::string_view s) that accepts only a complete, in-range integer (optional leading -, no spaces, no junk).

Previous: Measuring time Next: Challenge: a log formatter