在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();
当前回答
使用字符串流会更容易:
#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();
}
其他回答
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;
}
Use:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
我不知道,在纯C++中。但对你提到的内容稍作修改
string s = string(itoa(a));
应该有效,而且很短。
C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。
如果已安装Boost(您应该安装):
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);