在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++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

其他回答

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

string s = string(itoa(a));

应该有效,而且很短。

这对我有用-

我的代码:

#include <iostream>
using namespace std;

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

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

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

我通常使用以下方法:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

这里将详细描述。

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