在C++中将int转换为等价字符串的最简单方法是什么?我知道两种方法。有没有更简单的方法?

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

当前回答

char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

其他回答

char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

C++11引入了std::stoi(以及每种数字类型的变体)和std::to_string,这是C atoi和itoa的对应项,但用std::string表示。

#include <string> 

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

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

auto s = std::to_string(42);

注:请参见[string.converts](n3242中的21.5)

使用字符串流进行数字转换是危险的!

请参阅std::ostream::operator<<,其中告诉operator<插入格式化输出。

根据您当前的语言环境,大于三位数的整数可以转换为四位数的字符串,并添加额外的千位分隔符。

例如,int=1000可以转换为字符串1.001。这可能会使比较操作根本不起作用。

所以我强烈建议使用std::to_string方法。它更容易,做你期望的事情。

从std::到_string:

C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。

int i = 255;
std::string s = std::to_string(i);

在C++中,to_string()将通过将值表示为一系列字符来创建一个整数值的字符串对象。

我使用:

int myint = 0;
long double myLD = 0.0;

string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();

它适用于我的Windows和Linux g++编译器。