how to convert int to std::string
To convert an int
to a std::string
in C++, you can use the std::to_string()
function. Here are the steps to do it:
- Include the necessary header file:
#include <string>
- Declare an
int
variable and assign a value to it:
int num = 123;
- Use the
std::to_string()
function to convert theint
to astd::string
:
std::string str = std::to_string(num);
Explanation:
- The
std::to_string()
function is a part of the C++ Standard Library and is defined in the<string>
header. - It takes an
int
as an argument and returns an equivalentstd::string
representation of the number. - In the example above, we declare an
int
variablenum
and assign it a value of123
. - We then use the
std::to_string()
function to convertnum
to astd::string
and store the result in thestr
variable.
That's it! Now the int
value has been successfully converted to a std::string
using the std::to_string()
function.