Numbers and Strings
Converting Numbers to Strings
To combine numbers with strings, convert the numbers to string form first. Since C++11, the `to_string()` function makes this simple:
Example
#include <string>\n#include <iostream>\nusing namespace std;\n\nint main() {\n int age = 25;\n double price = 9.99;\n\n string ageStr = \"Age: \" + to_string(age);\n string priceStr = \"Price: \" + to_string(price);\n\n cout << ageStr << endl << priceStr;\n return 0;\n}
Output
Age: 25\nPrice: 9.990000
ℹ️ Note: `to_string` uses a default, non-locale format and prints many floating digits (typically six). For custom formatting, prefer iostream manipulators, `ostringstream`, or C++20 `std::format`.
String to Number Conversion
To convert strings back to numbers, use these functions from `
Example
#include <string>\n#include <iostream>\nusing namespace std;\n\nint main() {\n string numStr = \"123\";\n int num = stoi(numStr); // string to int\n double d = stod(\"3.14\"); // string to double\n float f = stof(\"2.718\"); // string to float\n\n cout << num * 2 << endl;\n cout << d * 2 << endl;\n cout << f * 2;\n return 0;\n}
Output
246\n6.28\n5.436
ℹ️ Note: `stoi/stol/stoll/stof/stod/stold` throw `std::invalid_argument` or `std::out_of_range` on bad input; validate or catch exceptions for robust code.
Formatting Numbers in Strings
For more control over how numbers are represented in strings, use `ostringstream` with manipulators:
Example
#include <sstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n int x = 42;\n double y = 3.14159;\n\n ostringstream oss;\n oss << \"The answer is \" << x << \" and pi is \" << fixed << setprecision(2) << y;\n string result = oss.str();\n\n cout << result;\n return 0;\n}
Output
The answer is 42 and pi is 3.14
ℹ️ Note: Include `<iomanip>` for manipulators like `fixed` and `setprecision`.