在C ++中从int转换为等效的string的最简单方法是什么。我知道两种方法。有没有更简单的方法?

(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 atoiitoa的对应物,但用std::string表示。

#include <string>

std::string s = std::to_string(42);


因此,这是我能想到的最短的方法。您甚至可以使用auto关键字省略命名类型:

auto s = std::to_string(42);


注意:请参见[string.conversions](n3242中为21.5)

关于c++ - 在C++中将int转换为字符串的最简单方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58915875/

10-11 23:07
查看更多