std::string containing a number can be converted into an integer type, or a floating point type, using conversion functions.
Note that all of these functions stop parsing the input string as soon as they encounter a non-numeric character, so
"123abc" will be converted into
std::ato* family of functions converts C-style strings (character arrays) to integer or floating-point types:
std::string ten = "10"; double num1 = std::atof(ten.c_str()); int num2 = std::atoi(ten.c_str()); long num3 = std::atol(ten.c_str());
long long num4 = std::atoll(ten.c_str());
However, use of these functions is discouraged because they return
0 if they fail to parse the string. This is bad because
0 could also be a valid result, if for example the input string was "0", so it is impossible to determine if the conversion actually failed.
std::sto* family of functions convert
std::strings to integer or floating-point types, and throw exceptions if they could not parse their input. You should use these functions if possible:
std::string ten = "10"; int num1 = std::stoi(ten); long num2 = std::stol(ten); long long num3 = std::stoll(ten); float num4 = std::stof(ten); double num5 = std::stod(ten); long double num6 = std::stold(ten);
Furthermore, these functions also handle octal and hex strings unlike the
std::ato* family. The second parameter is a pointer to the first unconverted character in the input string (not illustrated here), and the third parameter is the base to use.
0 is automatic detection of octal (starting with
0) and hex (starting with
0X), and any other value is the base to use
std::string ten = "10"; std::string ten_octal = "12"; std::string ten_hex = "0xA"; int num1 = std::stoi(ten, 0, 2); // Returns 2 int num2 = std::stoi(ten_octal, 0, 8); // Returns 10 long num3 = std::stol(ten_hex, 0, 16); // Returns 10 long num4 = std::stol(ten_hex); // Returns 0 long num5 = std::stol(ten_hex, 0, 0); // Returns 10 as it detects the leading 0x