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(idx);
cout << d << rest << "n"; // 99 red balloons

In the preceding code, the idx variable will be initialized with a value of 4, indicating that the space between the 5 and r is the first character that cannot be converted to a double.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset