在C ++中将int转换为字符串的最简单的方法 [英] Easiest way to convert int to string in C++
本文介绍了在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)
这篇关于在C ++中将int转换为字符串的最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文