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

当前回答

添加一些语法糖是相当容易的,它允许人们以流式的方式动态地编写字符串

#include <string>
#include <sstream>

struct strmake {
    std::stringstream s;
    template <typename T> strmake& operator << (const T& x) {
        s << x; return *this;
    }   
    operator std::string() {return s.str();}
};

现在,您可以向strmake()添加任何所需的内容(前提是为其定义了运算符<<(std::ostream&…)),并使用它代替std::string。

例子:

#include <iostream>

int main() {
    std::string x =
      strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
    std::cout << x << std::endl;
}

其他回答

使用普通标准stdio标头,可以将sprintf上的整数强制转换为缓冲区,如下所示:

#include <stdio.h>

int main()
{
    int x = 23;
    char y[2]; // The output buffer
    sprintf(y, "%d", x);
    printf("%s", y)
}

记住根据您的需要(字符串输出大小)注意缓冲区的大小。

电流C++

从C++11开始,有一个std::to_string函数为整数类型重载,因此可以使用如下代码:

int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);

标准将其定义为等同于使用sprintf(使用与提供的对象类型匹配的转换说明符,例如%d表示int)将其转换为足够大小的缓冲区,然后创建该缓冲区内容的std::字符串。

旧C++

对于较旧的(早于C++11)编译器,可能最常见的简单方法是将第二个选择打包到一个通常名为lexical_cast的模板中,例如Boost中的模板,因此代码如下:

int a = 10;
string s = lexical_cast<string>(a);

这样做的一个好处是它也支持其他类型的转换(例如,在相反的方向上也可以)。

还要注意,虽然Boost lexical_cast一开始只是写入字符串流,然后从流中提取,但现在它有了一些附加功能。首先,添加了相当多类型的专门化,因此对于许多常见类型,它比使用字符串流快得多。第二,它现在检查结果,因此(例如)如果您从字符串转换为int,如果字符串包含无法转换为int的内容(例如,1234将成功,但123abc将抛出),它可以抛出异常。

如果您需要将具有固定位数的整数快速转换为左填充“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;我认为它应该起作用。

我认为使用stringstream非常简单:

 string toString(int n)
 {
     stringstream ss(n);
     ss << n;
     return ss.str();
 }

 int main()
 {
    int n;
    cin >> n;
    cout << toString(n) << endl;
    return 0;
 }

您只需在定义变量(StringintStr)时使用String。每当需要该变量时,调用whateverFunction(intStr.toInt())