在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 <sstream>

int x = 42;          // The integer
string str;          // The string
ostringstream temp;  // 'temp' as in temporary
temp << x;
str = temp.str();    // str is 'temp' as string

或生成函数:

#include <sstream>

string IntToString(int a)
{
    ostringstream temp;
    temp << a;
    return temp.str();
}

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

string s = string(itoa(a));

应该有效,而且很短。

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

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

如果使用MFC,可以使用CString:

int a = 10;
CString strA;
strA.Format("%d", a);

Use:

#define convertToString(x) #x

int main()
{
    convertToString(42); // Returns const char* equivalent of 42
}