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

当前回答

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

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

其他回答

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

int a = 10;
CString strA;
strA.Format("%d", a);
namespace std
{
    inline string to_string(int _Val)
    {   // Convert long long to string
        char _Buf[2 * _MAX_INT_DIG];
        snprintf(_Buf, "%d", _Val);
        return (string(_Buf));
    }
}

现在可以使用to_string(5)。

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

应该有效,而且很短。

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

#include <boost/lexical_cast.hpp>

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