Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in C++.
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:
Next, we’ll look at another common parsing task: URLs.