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

当前回答

使用字符串流进行数字转换是危险的!

请参阅std::ostream::operator<<,其中告诉operator<插入格式化输出。

根据您当前的语言环境,大于三位数的整数可以转换为四位数的字符串,并添加额外的千位分隔符。

例如,int=1000可以转换为字符串1.001。这可能会使比较操作根本不起作用。

所以我强烈建议使用std::to_string方法。它更容易,做你期望的事情。

从std::到_string:

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

其他回答

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

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

#include <boost/lexical_cast.hpp>

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

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

#include <stdio.h>

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

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

这是另一个简单的方法

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

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

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

C++11引入了std::stoi(以及每种数字类型的变体)和std::to_string,这是C atoi和itoa的对应项,但用std::string表示。

#include <string> 

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

因此,这是我能想到的最短的方法。您甚至可以使用auto关键字省略对类型的命名:

auto s = std::to_string(42);

注:请参见[string.converts](n3242中的21.5)