如何最短地(最好是内联方式)将整数转换为字符串?欢迎使用STL和Boost库的答案。
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
std::ostringstream().operator<<(i).str()
吗? - kevinarpe嗯,在 C++11 之前,广为人知的方法是使用流操作符:
#include <sstream>
std::ostringstream s;
int i;
s << i;
std::string converted(s.str());
当然,你可以使用模板函数将其泛化为任何类型^^
#include <sstream>
template<typename T>
std::string toString(const T& value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
#include <sstream>
。 - Niki Romagnolistd::
;) - neuroboost::lexical_cast<std::string>(yourint)
来自 boost/lexical_cast.hpp
对于所有支持 std::ostream 的内容都适用,但速度不如例如 itoa
它甚至比 stringstream 或 scanf 更快:
lexical_cast
所带来的便利,但是感觉Boost在这种任务上显得过于笨重了。 - rubenvb如果您无法使用C++11中的std::to_string
,您可以按照cppreference.com上定义的方式编写:
std::string to_string( int value )
将带符号的十进制整数转换为与std::sprintf(buf, "%d", value)
在足够大的buf上产生相同内容的字符串。
实现
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
你可以更多地使用它。只需使用“%g”
将浮点数或双精度转换为字符串,使用“%x”
将整数转换为十六进制表示等等。这是一个非标准函数,但大多数常见的编译器都已经实现了它:
int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);
更新
C++11引入了几个std::to_string
重载(注意它默认为十进制)。
ostream
也可以使用,但当您需要将数字字符串保存为其他格式(如基于32位的格式)时,就不再适用于二进制、八进制或十六进制格式。 - Zac Howlanditoa()
和stricmp()
)被用作回答任何问题的解决方法。 - DevSolarsprintf
也可以完成OP的目标(尽管如果需要除常见基数数字以外的任何内容仍然缺乏灵活性)。 - Zac Howlandostringstream
或boost::lexical_cast
那样紧凑。operator<<()
支持的所有内容,甚至是组合形式。#include <sstream>
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
解释:
std::dec
是一种无副作用的方式,将匿名的ostringstream
转换为通用的ostream
,以便operator<<()
函数查找正确地适用于所有类型。(如果第一个参数是指针类型,则会出现问题。)
dynamic_cast
将类型返回到ostringstream
,因此您可以在其上调用str()
。
用法:
#include <string>
int main()
{
int i = 42;
std::string s1 = SSTR( i );
int x = 23;
std::string s2 = SSTR( "i: " << i << ", x: " << x );
return 0;
}
在包含<sstream>
之后,您可以使用此函数将int
转换为std::string
:
#include <sstream>
string IntToString (int a)
{
stringstream temp;
temp<<a;
return temp.str();
}
#include <iostream>
#include <locale>
#include <format>
int main()
{
using std::cout, std::endl;
auto const n = 42;
cout << std::format("{}", n) << endl;
cout << std::format("{:d}", n) << endl;
cout << std::format("{:#x}", n) << endl;
cout << std::format("{:#o}", n) << endl;
cout << std::format("{:#b}", n) << endl;
}
输出:
42
42
0x2a
052
0b101010
to_string
,例如:std::string s = std::to_string(42)
。 - user283145