在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++中将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::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)
其他回答
您只需在定义变量(StringintStr)时使用String。每当需要该变量时,调用whateverFunction(intStr.toInt())
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)
sprintf()非常适合格式转换。然后,可以像在1中那样将生成的C字符串分配给C++字符串。
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
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;
}