在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();
当前回答
我使用:
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++编译器。
其他回答
使用字符串流会更容易:
#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();
}
您只需在定义变量(StringintStr)时使用String。每当需要该变量时,调用whateverFunction(intStr.toInt())
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;
}
使用字符串流进行数字转换是危险的!
请参阅std::ostream::operator<<,其中告诉operator<插入格式化输出。
根据您当前的语言环境,大于三位数的整数可以转换为四位数的字符串,并添加额外的千位分隔符。
例如,int=1000可以转换为字符串1.001。这可能会使比较操作根本不起作用。
所以我强烈建议使用std::to_string方法。它更容易,做你期望的事情。
从std::到_string:
C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。
sprintf()非常适合格式转换。然后,可以像在1中那样将生成的C字符串分配给C++字符串。