在 C++ 中将 int 转换为字符串的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5590381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:27:41  来源:igfitidea点击:

Easiest way to convert int to string in C++

c++stringinttype-conversion

提问by Nemo

What is the easiest way to convert from intto equivalent stringin C++. I am aware of two methods. Is there any easier way?

在 C++ 中转换int为等效的最简单方法是什么string。我知道两种方法。有没有更简单的方法?

(1)

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

回答by Matthieu M.

C++11 introduces std::stoi(and variants for each numeric type) and std::to_string, the counterparts of the C atoiand itoabut expressed in term of std::string.

C++11 引入了std::stoi(和每个数字类型的变体)和std::to_string,C 的对应物atoianditoa但用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 autokeyword:

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

auto s = std::to_string(42);

Note: see [string.conversions](21.5in n3242)

注:参见[string.conversions] 21.5n3242

回答by DevSolar

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) withoutgoing through macro uglyness.

几年后与@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();
}

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:

由于“将...转换为字符串”是一个反复出现的问题,我总是在我的 C++ 源代码的中央标题中定义SSTR()宏:

#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.

以上是 C++98 兼容的(如果你不能使用 C++11 std::to_string),不需要任何第三方包含(如果你不能使用 Boost lexical_cast<>);不过,这两种其他解决方案都具有更好的性能。

回答by Rasoul

I usually use the following method:

我通常使用以下方法:

#include <sstream>

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

It is described in details here.

这里有详细的描述。

回答by Jerry Coffin

Probably the most common easy way wraps essentially your second choice into a template named lexical_cast, such as the one in Boost, so your code looks like this:

可能最常见的简单方法是将您的第二个选择本质上包装到一个名为 的模板中lexical_cast,例如Boost 中的模板,因此您的代码如下所示:

int a = 10;
string s = lexical_cast<string>(a);

One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).

这样做的一个好处是它也支持其他类型的转换(例如,在相反的方向也同样有效)。

Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int(e.g., 1234would succeed, but 123abcwould throw).

另请注意,虽然 Boost lexical_cast 开始时只是写入字符串流,然后从流中提取回来,但它现在有一些附加功能。首先,添加了很多类型的特化,因此对于许多常见类型,它比使用字符串流要快得多。其次,它现在检查结果,因此(例如)如果您从字符串转换为 an int,如果字符串包含无法转换为 an 的内容int(例如,1234会成功,但123abc会抛出),它会抛出异常.

As of C++11, there's a std::to_stringfunction overloaded for integer types, so you can use code like:

从 C++11 开始,有一个std::to_string为整数类型重载的函数,因此您可以使用如下代码:

int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);

The standard defines these as being equivalent to doing the conversion with sprintf(using the conversion specifier that matches the supplied type of object, such as %dfor int), into a buffer of sufficient size, then creating an std::stringof the contents of that buffer.

标准将这些定义为等效于将 with sprintf(使用与提供的对象类型匹配的转换说明符,例如%dfor int)转换为足够大小的缓冲区,然后创建std::string该缓冲区的内容。

回答by Kevin

If you have Boost installed (which you should):

如果您安装了 Boost(您应该安装):

#include <boost/lexical_cast.hpp>

int num = 4;
std::string str = boost::lexical_cast<std::string>(num);

回答by user2287915

It would be easier using stringstreams:

使用字符串流会更容易:

#include <sstream>

int x = 42;          // The integer
string str;          // The string
ostringstream temp;  // 'temp' as in temporary
temp << x;
str = temp.str();    // str is 'temp' as string

Or make a function:

或者做一个函数:

#include <sstream>

string IntToString(int a)
{
    ostringstream temp;
    temp << a;
    return temp.str();
}

回答by user541686

Not that I know of, in pure C++. But a little modification of what you mentioned

不是我所知道的,在纯 C++ 中。但是对您提到的内容稍作修改

string s = string(itoa(a));

should work, and it's pretty short.

应该可以工作,而且时间很短。

回答by vitaut

You can use std::to_stringavailable in C++11 as suggested by Matthieu M.:

您可以std::to_string按照Matthieu M. 的建议在 C++11 中使用available :

std::to_string(42);

Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_intfrom the {fmt}library to convert an integer to std::string:

或者,如果性能是至关重要的(例如,如果你做大量的转换),您可以使用fmt::format_int{} FMT库整数转换std::string

fmt::format_int(42).str();

Or a C string:

或者一个 C 字符串:

fmt::format_int f(42);
f.c_str();

The latter doesn't do any dynamic memory allocations and is more than 10 times faster than std::to_stringon Boost Karma benchmarks. See Fast integer to string conversion in C++for more details.

后者不进行任何动态内存分配,并且比std::to_stringBoost Karma 基准测试快 10 倍以上。有关更多详细信息,请参阅C++ 中的快速整数到字符串转换

Note that both are thread-safe.

请注意,两者都是线程安全的。

Unlike std::to_string, fmt::format_intdoesn't require C++11 and works with any C++ compiler.

std::to_string,fmt::format_int不需要 C++11 并与任何 C++ 编译器一起使用。

Disclaimer: I'm the author of the {fmt} library.

免责声明:我是 {fmt} 库的作者。

回答by Throwback1986

sprintf()is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.

sprintf()非常适合格式转换。然后,您可以像在 1 中所做的那样将结果 C 字符串分配给 C++ 字符串。

回答by Alex

First include:

首先包括:

#include <string>
#include <sstream>

Second add the method:

其次添加方法:

template <typename T>
string NumberToString(T pNumber)
{
 ostringstream oOStrStream;
 oOStrStream << pNumber;
 return oOStrStream.str();
}

Use the method like this:

使用这样的方法:

NumberToString(69);

or

或者

int x = 69;
string vStr = NumberToString(x) + " Hello word!."