在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();

当前回答

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

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

其他回答

这对我有用-

我的代码:

#include <iostream>
using namespace std;

int main()
{
    int n = 32;
    string s = to_string(n);
    cout << "string: " + s  << endl;
    return 0;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

我不知道,在纯C++中。但对你提到的内容稍作修改

string s = string(itoa(a));

应该有效,而且很短。

C++11为数字类型引入了std::to_string():

int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string

如果已安装Boost(您应该安装):

#include <boost/lexical_cast.hpp>

int num = 4;
std::string str = boost::lexical_cast<std::string>(num);