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

当前回答

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

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

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

其他回答

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)

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

#include <boost/lexical_cast.hpp>

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

Use:

#define convertToString(x) #x

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

在C++11中,我们可以使用“to_string()”函数将int转换为字符串:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int x = 1612;
    string s = to_string(x);
    cout << s<< endl;

    return 0;
}

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