Number Parsing in C++

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in C++.

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

int main() {
    // With stod, we parse a string to a double
    double f = std::stod("1.234");
    std::cout << f << std::endl;

    // For stoi, we parse a string to an integer
    int i = std::stoi("123");
    std::cout << i << std::endl;

    // stoi will recognize hex-formatted numbers
    int d = std::stoi("0x1c8", nullptr, 0);
    std::cout << d << std::endl;

    // For parsing unsigned integers, we use stoull
    unsigned long long u = std::stoull("789");
    std::cout << u << std::endl;

    // stoi is a convenience function for basic base-10 int parsing
    int k = std::stoi("135");
    std::cout << k << std::endl;

    // Parse functions throw exceptions on bad input
    try {
        std::stoi("wat");
    } catch (const std::invalid_argument& e) {
        std::cout << e.what() << std::endl;
    }

    return 0;
}

In C++, we use the <string> header for string handling and number parsing. The std::stod, std::stoi, and std::stoull functions are used for parsing floating-point numbers, integers, and unsigned long long integers respectively.

With std::stod, we parse a string to a double-precision floating-point number.

For std::stoi, we can parse a string to an integer. It can also recognize hex-formatted numbers when we specify the base as 0.

std::stoull is available for parsing unsigned long long integers.

These functions throw exceptions (std::invalid_argument or std::out_of_range) on bad input, which we can catch and handle.

To compile and run this program:

$ g++ -std=c++11 number_parsing.cpp -o number_parsing
$ ./number_parsing
1.234
123
456
789
135
stoi: no conversion

Next, we’ll look at another common parsing task: URLs.