How to convert a variable of type int to type string in C++? Today we will introduce two methods.

How to convert a variable of type int to type string in C++? Today we will introduce two methods.

The first method is to use the std::to_string() function introduced by the C++11 standard. This function can convert a numeric type variable to the corresponding string type. Here's a usage example:

#include <iostream>
#include <string>

int main()
{
    int num = 12345;
    std::string str = std::to_string(num);
    std::cout << str << std::endl;

    return 0;
}

The above code converts the integer variable num to a string type and outputs it to the console. When using this method, the header file <string> needs to be included.

The second way is to use the stringstream class. This class is defined in the header file <sstream>, which can be used to format input and output of various data types. Here's a usage example:

#include <iostream>
#include <sstream>

int main()
{
    int num = 12345;
    std::stringstream ss;
    ss << num;
    std::string str = ss.str();
    std::cout << str << std::endl;

    return 0;
}

The above code creates a stringstream object, writes the integer variable num into this object, and then uses the member function str() to convert the contents of the stringstream object into a string type and output it to the console.

The above are two methods of converting int type variables to string type. You can choose which method to use based on the specific situation.

Guess you like

Origin blog.csdn.net/CodeWG/article/details/132293564