在C ++中将int转换为字符串的最简单的方法
问题描述:
在C ++中,从int转换为等效字符串的最简单方法是什么。我知道两种方法。有更简单的方法吗?
What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?
1。
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
2。
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
答
C ++ 11引入 std :: stoi
(以及每个数字类型的变体)和 std :: to_string
,相应的的C atoi
和 itoa
,但以 std :: string
。
C++11 introduces std::stoi
(and variants for each numeric type) and std::to_string
, the counterparts of the C atoi
and itoa
but expressed in term of std::string
.
#include <string>
std::string s = std::to_string(42);
因此是我能想到的最短的方式。
is therefore the shortest way I can think of.
注意:请参阅 [string.conversions] (n3242中的 21.5 )
Note: see [string.conversions] (21.5 in n3242)