C++ Convert Strings and Numbers
Convert Strings and Numbers
In the Numbers and Strings chapter, you learned that "10" + "20" gives "1020", because the values are text, not numbers. You also saw that you cannot add a number to a string.
To calculate with a number that is stored as text, or to add a number to a text, you must convert it first. Use these functions from the <string> library:
stoi()converts a string to anintstod()converts a string to adoubleto_string()converts a number to a string
Convert a String to a Number
Use stoi() (string to int) to convert text to a whole number, so you can calculate with it:
Example
string x = "10";
string y = "20";
cout << x + y << "\n"; // 1020
cout << stoi(x) + stoi(y) << "\n"; // 30
Use stod() (string to double) for numbers with decimals:
Example
string price = "9.99";
double myPrice = stod(price);
cout << myPrice * 2; // 19.98
Note: stoi() needs a string that starts with a number. stoi("hello") stops the program with an error. You will learn how to handle errors like this in the Exceptions chapter.
Convert a Number to a String
Use to_string() to convert a number to a string. This lets you add a number to a text:
Example
int score = 100;
string text = "Score: " + to_string(score);
cout << text; // Score: 100
Note: When you use to_string() on a double, it always shows 6 decimals. to_string(9.5) gives "9.500000".