skip to content

In C++, what does std::stoi do with input such as "80abc" or "http", and how should a port parser check it?

level: juniorimportance: should knowfreq 50%

answer

  1. wraps strtol
  2. two exception types
  3. the idx out-parameter
  4. partial parse succeeds
  5. C++26 to_string for doubles

basics

~20 s

std::stoi calls strtol: it skips leading whitespace, converts the longest valid prefix, and returns 80 for "80abc". It throws std::invalid_argument when nothing converts ("http") and std::out_of_range when the value does not fit. Check idx equals the length to reject trailing junk.

solid answer

~40 s

`std::stoi(str, idx, base)` is specified in terms of `strtol(str.c_str(), ...)`. That shapes three behaviours. It **skips leading whitespace** and converts the **longest numeric prefix**, so `" 443"` gives 443 and `"80abc"` gives 80 without any error. It throws `std::invalid_argument` when no conversion is possible, as for `"http"`, and `std::out_of_range` when `strtol` reports `ERANGE` or the value does not fit in `int`. To reject partial input, pass a `std::size_t` through the `idx` parameter and require it to equal `str.size()`, then range-check the result for your domain (1 to 65535 for a port). The reverse direction, `std::to_string`, formats integers plainly; for floating point it used `%f` through C++23, so `to_string(1e-7)` is `"0.000000"`, and C++26 respecifies it as `std::format("{}", val)`.

code

cpp · 20 lines
cpp
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    for (std::string port : {"8080", "  443", "80abc", "http", "99999999999"}) {
        try {
            std::size_t used = 0;
            int value = std::stoi(port, &used);
            std::cout << '"' << port << "\" -> " << value
                      << " (used " << used << " of " << port.size() << ")\n";
        } catch (const std::invalid_argument& e) {
            std::cout << '"' << port << "\" -> invalid_argument\n";
        } catch (const std::out_of_range& e) {
            std::cout << '"' << port << "\" -> out_of_range\n";
        }
    }
    std::cout << std::to_string(42) << ' ' << std::to_string(0.1) << ' '
              << std::to_string(1e-7) << '\n';
}

go deeper

for a junior

Know that std::stoi throws std::invalid_argument or std::out_of_range, and that std::to_string turns numbers into text.

for a middle

Explain the strtol heritage: whitespace skipping, partial parses that succeed, and the idx parameter that exposes them.

for a senior

Write strict parsers that check idx and domain ranges, and reach for from_chars in hot or exception-free code.

for a principal

Set one parsing approach for the codebase so configuration and protocol input are validated the same strict way everywhere.

## The family `<string>` provides two directions of numeric conversion: - **Text to number:** `std::stoi`, `std::stol`, `std::stoul`, `std::stoll`, `std::stoull` for integers, and `std::stof`, `std::stod`, `std::stold` for floating point. Each takes `const std::string&`, an optional `std::size_t* idx`, and for the integer ones a `base` defaulting to 10. - **Number to text:** `std::to_string`, overloaded for every integer and floating type. They are the convenient, exception-throwing layer over C's `strtol` family and `sprintf`, and their quirks come straight from that heritage. ## What stoi accepts The standard specifies `stoi` as calling `strtol(str.c_str(), ptr, base)` and returning the result. `strtol` skips leading whitespace, accepts an optional sign, then converts as many digits as it can and stops at the first character that does not fit. So, as a run on this machine prints: | input | result | characters used (`idx`) | |---|---|---| | `"8080"` | 8080 | 4 of 4 | | `" 443"` | 443 | 5 of 5 | | `"80abc"` | 80 | 2 of 5 | | `"http"` | throws `std::invalid_argument` | none | | `"99999999999"` | throws `std::out_of_range` | none | The third row is the trap: **a partial parse is a success**. A port parser that just calls `std::stoi(text)` accepts `"80abc"` as port 80. The `base` argument is passed straight to `strtol` as well: - `std::stoi("ff", nullptr, 16)` is 255; - with base 0 the prefix decides, so `std::stoi("0x1F", nullptr, 0)` is 31 and `std::stoi("010", nullptr, 0)` is 8, an octal surprise; - with the default base 10, `std::stoi("010")` is 10. ## The two exceptions - `std::invalid_argument` when `strtol` reports that **no conversion** can be performed: empty text, only whitespace, or no leading digits. - `std::out_of_range` when `strtol` sets `errno` to `ERANGE`, or when the value does not fit the return type. The second clause matters for `stoi`, which converts with `long` and must still reject values outside `int`. Both derive from `std::logic_error`, and both are thrown only on those conditions; trailing junk throws nothing. ## A strict port parser 1. Call `std::stoi(text, &used)`. 2. Reject the input unless `used == text.size()`; that refuses `"80abc"` and trailing spaces. 3. Decide whether leading whitespace is acceptable; `stoi` silently allows it. 4. Range-check for the domain, here `1 <= port && port <= 65535`. 5. Catch `std::invalid_argument` and `std::out_of_range` and report a parse error, not a crash. Where exceptions are unwelcome, such as a hot loop or a build without exceptions, `std::from_chars` from `<charconv>` (C++17) does the same job: it does not skip whitespace, does not allocate, reports errors through a returned `errc`, and returns a pointer to the first unparsed character. ## Choosing the conversion tool | tool | on bad input | allocates | skips whitespace | |---|---|---|---| | `std::stoi` | throws `invalid_argument` or `out_of_range` | only if a `std::string` must be built to call it | yes | | `std::from_chars` (C++17) | returns an `std::errc` | no | no | | `std::strtol` | returns 0 with the end pointer unmoved, or a clamped value with `errno` set to `ERANGE` | no | yes | The `strtol` row is the C function the other two are measured against; it reports failure only through its end pointer and `errno`, which are easy to forget to check. ## to_string and its floating-point surprise `std::to_string(42)` yields `"42"`, as expected. The floating-point overloads are where versions differ: - **Through C++23** they are specified like `sprintf` with `%f`: always six digits after the point, so `to_string(0.1)` is `"0.100000"` and `to_string(1e-7)` is `"0.000000"`, losing the value entirely, and the decimal point follows the global C locale. - **C++26** respecifies every overload as returning `std::format("{}", val)`, the shortest text that round-trips, so `to_string(1e-7)` becomes `"1e-07"`; the integer overloads also become `constexpr`. The standard's compatibility annex lists it as a change that may produce different output. - Library support is uneven: libstdc++ 16 implements the C++26 behaviour, while libc++ on this machine still prints `0.000000` even with `-std=c++2c`. So for floating-point text that must be precise, or stable across standards, use `std::format` or `std::to_chars` directly rather than `to_string`.

  • When would you choose std::from_chars over std::stoi?
    When exceptions or allocations are unwelcome, or when the input is not a `std::string`. `std::from_chars` (C++17) parses a `[first, last)` character range, returns a `std::from_chars_result` with a pointer to the first unparsed character and an `std::errc`, never throws, never allocates and never skips whitespace or consults the locale. Check `ec == std::errc{}` and that `ptr == last`.
  • Why can std::stoi throw std::out_of_range for a value that strtol converted without error?
    `stoi` uses `strtol`, which returns a `long`. On platforms where `long` is 64 bits, a value such as 3,000,000,000 fits in `long`, so `strtol` reports no `ERANGE`, but it does not fit in `int`. The standard requires `out_of_range` when the converted value is outside the return type's range, so `stoi` checks and throws.

  • std::stoi("80abc") throws because the text is not a number.
  • std::stoi returns 0 to signal a parse failure.
  • std::stoi rejects leading spaces like " 443".
  • std::to_string(0.1) gives the shortest text, "0.1", in C++17.
  • Catching std::invalid_argument alone covers every stoi failure.

Assumes C++23 for to_string's %f output; C++26 respecifies it as std::format("{}", val), and support varies by library.