Short answer
std::to_string takes a number and returns a std::string that holds its decimal text. For example, std::to_string(42) returns "42". It is declared in <string>, and it is a free function, so you call it as std::to_string(x), not x.to_string(). For the wider topic of turning numbers into text, see c convert int to string.
A basic example
#include <iostream>
#include <string>
int main() {
std::string text = std::to_string(42);
std::cout << text << "\n"; // 42
}
What it returns for different types
The standard library provides std::to_string overloads for the integer types, and for float, double, and long double. A few results show how it behaves:
std::to_string(-7)returns"-7".std::to_string(3.14)returns"3.140000".std::to_string('A')returns"65".
There is no overload for char. The char is promoted to int, so the int overload runs and returns the character’s code.
Why 3.14 becomes 3.140000
For a double, the text is produced the way printf formats it with %f, which always shows six digits after the decimal point. The %f format behind this output is covered in What is %f and %d in C?
Very large doubles print every digit, with no exponent. For example, std::to_string(1e20) returns a long string of digits followed by .000000. A very small value such as 0.0000001 comes out as "0.000000", because only six decimal places are kept.
Using it in a message
#include <iostream>
#include <string>
int main() {
int count = 3;
std::string label = "Items: " + std::to_string(count);
std::cout << label << "\n"; // Items: 3
}
Using the + operator to add text works because std::to_string returns a std::string.
Passing a char
Passing a char gives its numeric code, not the letter. std::to_string('A') returns "65". If you want the letter as text, build a string from the character instead, such as std::string(1, c). The reason a char becomes a number is explained in c char to int.
When to use something else
std::to_string does not let you choose the number of decimal places, a field width, or the notation. For more control, two options are:
std::ostringstreamfrom<sstream>, used withstd::fixedandstd::setprecisionfrom<iomanip>, which lets you choose the number of decimal places.std::formatfrom<format>, a formatting function added in C++20.
Going the other way, from text back to a number, is covered in c convert string to int.