How to Use to_string in C++: Convert Numbers to Strings Easily
In C++, use the
to_string function to convert numbers like int, float, or double into std::string. Simply call std::to_string(value) where value is the number you want to convert.Syntax
The to_string function is used to convert numeric values to strings. It is part of the std namespace and works with types like int, long, float, double, and long long.
std::to_string(value): Convertsvalueto astd::string.value: A numeric variable or literal you want to convert.
cpp
std::string s = std::to_string(123);Example
This example shows how to convert different numeric types to strings using std::to_string and print them.
cpp
#include <iostream> #include <string> int main() { int i = 42; float f = 3.14f; double d = 2.71828; std::string si = std::to_string(i); std::string sf = std::to_string(f); std::string sd = std::to_string(d); std::cout << "int to string: " << si << "\n"; std::cout << "float to string: " << sf << "\n"; std::cout << "double to string: " << sd << "\n"; return 0; }
Output
int to string: 42
float to string: 3.140000
double to string: 2.718280
Common Pitfalls
Some common mistakes when using to_string include:
- Not including the
<string>header, which causes compilation errors. - Expecting
to_stringto format floating-point numbers with fewer decimals; it defaults to 6 decimal places. - Using
to_stringon non-numeric types, which is not supported.
To control floating-point formatting, use std::ostringstream instead.
cpp
/* Wrong: missing #include <string> */ // std::string s = to_string(10); // Error: to_string not found /* Right: include string and use std::to_string */ #include <string> std::string s = std::to_string(10);
Quick Reference
| Type | Usage Example | Resulting String |
|---|---|---|
| int | std::to_string(123) | "123" |
| float | std::to_string(3.14f) | "3.140000" |
| double | std::to_string(2.71828) | "2.718280" |
| long long | std::to_string(1234567890123LL) | "1234567890123" |
Key Takeaways
Use std::to_string(value) to convert numbers to strings easily in C++.
Include the header and use the std namespace for to_string.
to_string formats floating-point numbers with 6 decimal places by default.
to_string only works with numeric types, not custom or non-numeric types.
For custom formatting of numbers, consider using string streams instead.