Converting a String to a Number Type in C++
std::stoi
, std::stol
, and std::stoll
take a string and return an integer type. Their prototypes are like:
int stoi ( const std::string& str, std::size_t* pos = nullptr, int base = 10 ); int stoi ( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 );
where
- str is the string to convert,
- pos is the address of an integer to store the number of characters processed, and
- base is the number base, commonly 10, 2, 8...
These (global) functions are defined in header <string
.
The exceptions (<stdexcept>
) that may be thrown are:
std::invalid_argument
if no conversion could be performed, andstd::out_of_range
if the converted value would fall out of the range of the result type or if the underlying function (std::strtol
orstd::strtoll
) sets errno to ERANGE.
This is an example showing how to use them:
#include <iomanip> #include <iostream> #include <stdexcept> #include <string> #include <utility> int main() { const auto data = { "45", "+45", " -45", "3.14159", "31337 with words", "words and 2", "12345678901", }; for (const std::string s : data) { std::size_t pos{}; try { std::cout << "std::stoi(" << std::quoted(s) << "): "; const int i{std::stoi(s, &pos)}; std::cout << i << "; pos: " << pos << '\n'; } catch (std::invalid_argument const& ex) { std::cout << "std::invalid_argument::what(): " << ex.what() << '\n'; } catch (std::out_of_range const& ex) { std::cout << "std::out_of_range::what(): " << ex.what() << '\n'; const long long ll{std::stoll(s, &pos)}; std::cout << "std::stoll(" << std::quoted(s) << "): " << ll << "; pos: " << pos << '\n'; } } std::cout << "\nCalling with different radixes:\n"; for (const auto& [s, base] : {std::pair<const char*, int> {"11", 2}, {"22", 3}, {"33", 4}, {"77", 8}, {"99", 10}, {"FF", 16}, {"jJ", 20}, {"Zz", 36}}) { const int i{std::stoi(s, nullptr, base)}; std::cout << "std::stoi(" << std::quoted(s) << ", nullptr, " << base << "): " << i << '\n'; } }
...