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

当前回答

您可以按照Matthieu M.的建议使用C++11中提供的std::to_string:

std::string s = std::to_string(42);

或者,如果性能非常关键(例如,如果进行大量转换),可以使用{fmt}库中的fmt::format_int将整数转换为std::string:

std::string s = fmt::format_int(42).str();

或C字符串:

fmt::format_int f(42);
const char* s = f.c_str();

后者不执行任何动态内存分配,比BoostKarma基准测试上std::to_string的libstdc++实现快70%以上。有关详细信息,请参阅每秒将一亿个整数转换为字符串。

免责声明:我是{fmt}库的作者。

其他回答

char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

这是另一个简单的方法

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

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

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

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

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

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

#include <boost/lexical_cast.hpp>

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

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

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