Strings and numbers
The Standard Library contains various functions and classes to convert between C++ strings and numeric values.
Converting strings to numbers
The C++ standard library contains functions with names like stod
and stoi
that convert a C++ string
object to a numeric value (stod
converts to a double
and stoi
converts to an integer
). For example:
double d = stod("10.5"); d *= 4; cout << d << "n"; // 42
This will initialize the floating-point variable d
with a value of 10.5
, which is then used in a calculation and the result is printed on the console. The input string may have characters that cannot be converted. If this is the case then the parsing of the string ends at that point. You can provide a pointer to a size_t
variable, which will be initialized to the location of the first character that cannot be converted:
string str = "49.5 red balloons"; size_t idx = 0; double d = stod(str, &idx); d *= 2; string rest = str.substr...