Easiest way to convert int to string in C++

后端 未结 28 2280
甜味超标
甜味超标 2020-11-21 06:42

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)



        
28条回答
  •  抹茶落季
    2020-11-21 07:11

    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 type-agnostic solution (preserved below) without going through macro uglyness.

    // variadic template
    template < typename... Args >
    std::string sstr( Args &&... args )
    {
        std::ostringstream sstr;
        // fold expression
        ( sstr << std::dec << ... << args );
        return 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 
    
    #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.

提交回复
热议问题