C++ to_string Function: Convert Numbers to Strings

In C++, the to_string() function is used to convert various data types (such as integers, floating-point numbers, etc.) into string types. It is a function in the C++ standard library header file.

The to_string() function has multiple overloaded versions that can accept different input parameter types, such as int, long, float, double, and so on. It converts the values of these numeric types into their corresponding string representations.

Here is an example of using the to_string() function:


#include <iostream>

#include <string>



int main() {

    int num = 42;

    double pi = 3.14159;



    std::string numStr = std::to_string(num);

    std::string piStr = std::to_string(pi);



    std::cout << "Number: " << numStr << std::endl;

    std::cout << "Pi: " << piStr << std::endl;



    return 0;

}

Output results:


Number: 42

Pi: 3.141590

In the example above, the std::to_string() function is used to convert integers and floating-point numbers into strings, stored in the variables numStr and piStr. They can then be passed to std::cout for output.

The to_string() function in C++ is very handy as it helps to easily convert data of other types into strings for string manipulation, concatenation, and other operations.

bannerAds