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

当前回答

C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。

其他回答

sprintf()非常适合格式转换。然后,可以像在1中那样将生成的C字符串分配给C++字符串。

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

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

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)

如果您需要将具有固定位数的整数快速转换为左填充“0”的char*,这是little-endian体系结构(所有x86、x86_64和其他)的示例:

如果要转换两位数:

int32_t s = 0x3030 | (n/10) | (n%10) << 8;

如果要转换三位数:

int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;

如果要转换四位数:

int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;

如此类推,直到七位数。在本例中,n是给定的整数。转换后,它的字符串表示形式可以访问为(char*)&s:

std::cout << (char*)&s << std::endl;

注意:如果您需要使用大端字节顺序,虽然我没有测试它,但这里有一个示例:对于三位数,它是int32_ts=0x00303030|(n/100)<<24|(n/10%10)<<16|(n/10)<<8;对于四位数(64位拱门):int64_t s=0x0000000030303030 |(n/1000)<<56 |(n/100%10)<<48 |(n/10%10)<<40 |(n/10%)<<32;我认为它应该起作用。

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