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

当前回答

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

其他回答

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

#include <stdio.h>

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

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

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

#include <boost/lexical_cast.hpp>

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

在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++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。

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