在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 <iostream>
using namespace std;

int main()
{
    int n = 32;
    string s = to_string(n);
    cout << "string: " + s  << endl;
    return 0;
}

其他回答

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

我不知道,在纯C++中。但对你提到的内容稍作修改

string s = string(itoa(a));

应该有效,而且很短。

string number_to_string(int x) {

    if (!x)
        return "0";

    string s, s2;
    while(x) {
        s.push_back(x%10 + '0');
        x /= 10;
    }
    reverse(s.begin(), s.end());
    return s;
}

这是另一个简单的方法

char str[100];
sprintf(str, "%d", 101);
string s = str;

sprintf是一种众所周知的将任何数据插入所需格式的字符串的方法。

您可以将char*数组转换为字符串,如第三行所示。

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

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