在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++11引入了std::stoi(以及每种数字类型的变体)和std::to_string,这是C atoi和itoa的对应项,但用std::string表示。

#include <string> 

std::string s = std::to_string(42);

因此,这是我能想到的最短的方法。您甚至可以使用auto关键字省略对类型的命名:

auto s = std::to_string(42);

注:请参见[string.converts](n3242中的21.5)

其他回答

int i = 255;
std::string s = std::to_string(i);

在C++中,to_string()将通过将值表示为一系列字符来创建一个整数值的字符串对象。

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<>);但这两种解决方案都有更好的性能。

char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

Use:

#include<iostream>
#include<string>

std::string intToString(int num);

int main()
{
    int integer = 4782151;

    std::string integerAsStr = intToString(integer);

    std::cout << "integer = " << integer << std::endl;
    std::cout << "integerAsStr = " << integerAsStr << std::endl;

    return 0;
}

std::string intToString(int num)
{
    std::string numAsStr;
    bool isNegative = num < 0;
    if(isNegative) num*=-1;

    do
    {
       char toInsert = (num % 10) + 48;
       numAsStr.insert(0, 1, toInsert);

       num /= 10;
    }while (num);
  
    return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}

添加一些语法糖是相当容易的,它允许人们以流式的方式动态地编写字符串

#include <string>
#include <sstream>

struct strmake {
    std::stringstream s;
    template <typename T> strmake& operator << (const T& x) {
        s << x; return *this;
    }   
    operator std::string() {return s.str();}
};

现在,您可以向strmake()添加任何所需的内容(前提是为其定义了运算符<<(std::ostream&…)),并使用它代替std::string。

例子:

#include <iostream>

int main() {
    std::string x =
      strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
    std::cout << x << std::endl;
}