Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::stoi — converting text to int

std::stoi from <string> converts an initial portion of text to int. It lets you specify the numeric base and retrieve the position where conversion stopped. It does not require consuming the entire string and reports errors through exceptions.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <string>

/* Overload synopsis (declarations provided by <string>):
namespace std {
    int stoi(const string& str, size_t* idx = nullptr, int base = 10);
    int stoi(const wstring& str, size_t* idx = nullptr, int base = 10);
}
*/

std::stoi, declared in <string>, returns an int value read from text. Overloads accept std::string and std::wstring. The base parameter specifies the numeric base and defaults to 10. The only valid values are 0 (automatic base detection) and integers from 2 through 36 inclusive. Other values are outside the underlying conversion's contract. If base comes from an untrusted source, validate it before the call: catching std::invalid_argument and std::out_of_range is not a portable way to validate the base.

Conversion may stop before the end of the text: "42px" produces 42, not an error. After a successful call with idx != nullptr, the function stores the index of the first unconverted element in *idx. The default nullptr discards this information. If the entire string must be consumed, check pos == text.size() after successful conversion.

If no conversion is possible, the function throws std::invalid_argument. A result outside the range of int, or a range error in the underlying conversion, causes std::out_of_range. Handle both exceptions when processing untrusted data; after an exception, do not treat idx as a conversion result.

The example prints 42, then index 2, then the remaining px. It demonstrates the difference between successfully converting an initial portion and validating the entire input. The source documentation is a live working draft, not a frozen C++23 edition; the example is intended for local checking in C++23 mode, without attesting a production runtime.

Examples

#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    const std::string text = "42px";
    std::size_t pos = 0;

    try {
        const int value = std::stoi(text, &pos, 10);
        std::cout << value << '\n';
        std::cout << pos << '\n';
        std::cout << text.substr(pos) << '\n';
    } catch (const std::invalid_argument&) {
        std::cout << "invalid_argument\n";
    } catch (const std::out_of_range&) {
        std::cout << "out_of_range\n";
    }
}

Result

42
2
px

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources