This post will discuss how to convert int to a string in C++.
1. Using std::to_string
function
The most common and efficient way is to use the std::to_string
function introduced with C++11, which returns a string representation of the specified value. It is overloaded for all data types.
We can also use std::to_wstring
, which returns std::wstring
.
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <iostream>
#include <string>
int main()
{
int i = 10;
std::string s = std::to_string(i);
std::cout << s << std::endl;
return 0;
}
|
Output:
10
2. Using string streams
Another good alternative is to use the stringstream
to convert between strings and other data types. The idea is to insert a given integer into the stream and then write contents of its buffer to the std::string
using its str()
function. We need to include the <sstream>
header file for this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <iostream>
#include <string>
#include <sstream>
int main()
{
int i = 10;
std::stringstream ss;
ss << i;
std::string s = ss.str();
std::cout << s << std::endl;
return 0;
}
|
Output:
10
3. Using boost lexical_cast
We can also use the boost lexical_cast library for converting an int to a string in C++. Please note that this solution is just a less-verbose alternative to the previous approach as lexical_cast
uses streams behind the scenes.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main()
{
int i = 10;
std::string s = boost::lexical_cast<std::string>(i);
std::cout << s << std::endl;
return 0;
}
|