在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();
}
其他回答
在C++11中,我们可以使用“to_string()”函数将int转换为字符串:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 1612;
string s = to_string(x);
cout << s<< endl;
return 0;
}
我不知道,在纯C++中。但对你提到的内容稍作修改
string s = string(itoa(a));
应该有效,而且很短。
我使用:
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();
}
您可以按照Matthieu M.的建议使用C++11中提供的std::to_string:
std::string s = std::to_string(42);
或者,如果性能非常关键(例如,如果进行大量转换),可以使用{fmt}库中的fmt::format_int将整数转换为std::string:
std::string s = fmt::format_int(42).str();
或C字符串:
fmt::format_int f(42);
const char* s = f.c_str();
后者不执行任何动态内存分配,比BoostKarma基准测试上std::to_string的libstdc++实现快70%以上。有关详细信息,请参阅每秒将一亿个整数转换为字符串。
免责声明:我是{fmt}库的作者。