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

其他回答

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

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

int a = 10;
CString strA;
strA.Format("%d", a);
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

使用计数器类型的算法转换为字符串。我从编程Commodore 64计算机中获得了这种技术。它也适用于游戏编程。

你取整数,取每一个10次幂的数字。所以假设整数是950。如果整数等于或大于100000,则减去100000并将字符串中的计数器增加为[“000000”];继续这样做,直到没有更多的数字在位置100000。再降低10次方。如果整数等于或大于10000,则减去10000,并在[“000000”]+1位置增加字符串中的计数器;一直这样做,直到10000位不再有数字。再降低10次方重复该模式

我知道950太小了,不能作为一个例子,但我希望你能理解。

使用字符串流会更容易:

#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();
}