Meilleur moyen de convertir int en chaîne en C+

Mots clés : c++stringinttype-conversionc++

meilleur 5 Réponses Meilleur moyen de convertir int en chaîne en C+

vote vote

99

#include <string>   std::string s = std::to_string(42); 
auto s = std::to_string(42); 
vote vote

82

// 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 ) ); 
#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 ) ); 
vote vote

78

#include <sstream>  template <typename T>   std::string NumberToString ( T Number )   {      std::ostringstream ss;      ss << Number;      return ss.str();   } 
vote vote

67

int a = 20; std::string s = std::to_string(a); // or: auto s = std::to_string(a); 
int a = 10; string s = lexical_cast<string>(a); 
vote vote

56

#include <boost/lexical_cast.hpp>  int num = 4; std::string str = boost::lexical_cast<std::string>(num); 

Questions similaires