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"; ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.