在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();
当前回答
使用字符串流进行数字转换是危险的!
请参阅std::ostream::operator<<,其中告诉operator<插入格式化输出。
根据您当前的语言环境,大于三位数的整数可以转换为四位数的字符串,并添加额外的千位分隔符。
例如,int=1000可以转换为字符串1.001。这可能会使比较操作根本不起作用。
所以我强烈建议使用std::to_string方法。它更容易,做你期望的事情。
从std::到_string:
C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。
其他回答
sprintf()非常适合格式转换。然后,可以像在1中那样将生成的C字符串分配给C++字符串。
电流C++
从C++11开始,有一个std::to_string函数为整数类型重载,因此可以使用如下代码:
int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);
标准将其定义为等同于使用sprintf(使用与提供的对象类型匹配的转换说明符,例如%d表示int)将其转换为足够大小的缓冲区,然后创建该缓冲区内容的std::字符串。
旧C++
对于较旧的(早于C++11)编译器,可能最常见的简单方法是将第二个选择打包到一个通常名为lexical_cast的模板中,例如Boost中的模板,因此代码如下:
int a = 10;
string s = lexical_cast<string>(a);
这样做的一个好处是它也支持其他类型的转换(例如,在相反的方向上也可以)。
还要注意,虽然Boost lexical_cast一开始只是写入字符串流,然后从流中提取,但现在它有了一些附加功能。首先,添加了相当多类型的专门化,因此对于许多常见类型,它比使用字符串流快得多。第二,它现在检查结果,因此(例如)如果您从字符串转换为int,如果字符串包含无法转换为int的内容(例如,1234将成功,但123abc将抛出),它可以抛出异常。
namespace std
{
inline string to_string(int _Val)
{ // Convert long long to string
char _Buf[2 * _MAX_INT_DIG];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
现在可以使用to_string(5)。
C++20:std::format现在将是惯用的方式。
C++17:
几年后,在与@v.oddou的讨论中,C++17提供了一种方法来实现最初基于宏的类型不可知的解决方案(保留在下面),而不需要经历宏的丑陋。
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
用法:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
C++98:
由于“将…转换为字符串”是一个反复出现的问题,我总是在C++源代码的中心标题中定义SSTR()宏:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
使用尽可能简单:
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
以上是C++98兼容的(如果您不能使用C++11 std::to_string),并且不需要任何第三方包含(如果您无法使用Boost lexical_cast<>);但这两种解决方案都有更好的性能。
使用字符串流进行数字转换是危险的!
请参阅std::ostream::operator<<,其中告诉operator<插入格式化输出。
根据您当前的语言环境,大于三位数的整数可以转换为四位数的字符串,并添加额外的千位分隔符。
例如,int=1000可以转换为字符串1.001。这可能会使比较操作根本不起作用。
所以我强烈建议使用std::to_string方法。它更容易,做你期望的事情。
从std::到_string:
C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。