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)


Picking up a discussion with @v.oddou a couple of years later, C++17 has finally delivered a way to do the originally macro-based solution (preserved below) without going through macro uglyness.

template < typename... Args >
std::string sstr( Args &&... args )
{
    std::ostringstream sstr;
    ( sstr << std::dec << ... << args );
    return static_cast< std::ostringstream & >( sstr ).str();
}

Usage:

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 ) );

Original answer:

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/20966.html

上一篇: 临时工的生命周期

下一篇: 将int转换为C ++字符串的最简单方法