Easiest way to convert int to string in C++
What is the easiest way to convert from int
to equivalent string
in C++. I am aware of two methods. Is there any easier way?
(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++11 introduces std::stoi
(and variants for each numeric type) and std::to_string
, the counterparts of the C atoi
and itoa
but expressed in term of std::string
.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto
keyword:
auto s = std::to_string(42);
Note: see [string.conversions] ( 21.5 in n3242)
Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >(
( std::ostringstream() << std::dec << x ) ).str()
Usage is as easy as could be:
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 ) );
The above is C++98 compatible (if you cannot use C++11 std::to_string
), and does not need any third-party includes (if you cannot use Boost lexical_cast<>
); both these other solutions have a better performance though.
I usually use the following method:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
described in details here.
链接地址: http://www.djcxy.com/p/3560.html上一篇: 为什么列表在没有引用的情况下传递给像ref一样传递的函数?
下一篇: 将int转换为C ++字符串的最简单方法