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

int x = 42;          // The integer
string str;          // The string
ostringstream temp;  // 'temp' as in temporary
temp << x;
str = temp.str();    // str is 'temp' as string

或生成函数:

#include <sstream>

string IntToString(int a)
{
    ostringstream temp;
    temp << a;
    return temp.str();
}

其他回答

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)

我使用:

int myint = 0;
long double myLD = 0.0;

string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();

它适用于我的Windows和Linux g++编译器。

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

电流C++

从C++11开始,有一个std::to_string函数为整数类型重载,因此可以使用如下代码:

int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);

标准将其定义为等同于使用sprintf(使用与提供的对象类型匹配的转换说明符,例如%d表示int)将其转换为足够大小的缓冲区,然后创建该缓冲区内容的std::字符串。

旧C++

对于较旧的(早于C++11)编译器,可能最常见的简单方法是将第二个选择打包到一个通常名为lexical_cast的模板中,例如Boost中的模板,因此代码如下:

int a = 10;
string s = lexical_cast<string>(a);

这样做的一个好处是它也支持其他类型的转换(例如,在相反的方向上也可以)。

还要注意,虽然Boost lexical_cast一开始只是写入字符串流,然后从流中提取,但现在它有了一些附加功能。首先,添加了相当多类型的专门化,因此对于许多常见类型,它比使用字符串流快得多。第二,它现在检查结果,因此(例如)如果您从字符串转换为int,如果字符串包含无法转换为int的内容(例如,1234将成功,但123abc将抛出),它可以抛出异常。

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