What is the usage of the to_string function in C++?

In C++, the to_string function is used to convert a numerical value into a string. It takes a numerical value as input and returns the corresponding string representation.

The usage of the to_string function is as follows:

  1. Convert integers to strings.
int num = 123;
std::string str = std::to_string(num);

In the example above, the integer 123 is converted into the string “123”.

  1. Convert floating point number to string.
double num = 3.14;
std::string str = std::to_string(num);

In the example above, the floating point number 3.14 is converted to the string “3.14”.

  1. Convert other data types to strings.

The to_string function can also convert other numerical types (such as long, float, etc.) into a string.

long num = 9876543210;
std::string str = std::to_string(num);

In the example above, the long integer 9876543210 is converted to the string “9876543210”.

It is important to note that the to_string function returns a temporary std::string object, not a C-style string (char*). If you need to use a C-style string, you can obtain it by calling the c_str() function.

int num = 123;
std::string str = std::to_string(num);
const char* cstr = str.c_str();

In the above example, convert a C++ string to a C-style string.

bannerAds