C++ 如何连接 std::string 和 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/191757/
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-27 13:34:59  来源:igfitidea点击:

How to concatenate a std::string and an int?

c++intconcatenationstdstring

提问by Obediah Stane

I thought this would be really simple but it's presenting some difficulties. If I have

我认为这会很简单,但它带来了一些困难。如果我有

std::string name = "John";
int age = 21;

How do I combine them to get a single string "John21"?

我如何将它们组合成一个字符串"John21"

回答by DannyT

In alphabetical order:

按字母顺序:

std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
  1. is safe, but slow; requires Boost(header-only); most/all platforms
  2. is safe, requires C++11 (to_string()is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. (ditto)
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream>(from standard C++)
  7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft(header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string()call in a single statement), fast; requires STLSoft(header-only); Windows-only
  11. is safe, but slow; requires Poco C++; most/all platforms
  1. 安全,但速度慢;需要Boost(仅标题);大多数/所有平台
  2. 是安全的,需要 C++11(to_string()已经包含在 中#include <string>
  3. 安全、快捷;需要FastFormat,它必须被编译;大多数/所有平台
  4. 同上
  5. 安全、快捷;需要{fmt} 库,它可以被编译或在仅标头模式下使用;大多数/所有平台
  6. 安全、缓慢且冗长;需要#include <sstream>(来自标准 C++)
  7. 脆弱(您必须提供足够大的缓冲区)、快速且冗长;itoa() 是一个非标准扩展,不保证适用于所有平台
  8. 脆弱(您必须提供足够大的缓冲区)、快速且冗长;什么都不需要(是标准的 C++);所有平台
  9. 很脆弱(您必须提供足够大的缓冲区),可能是最快的转换,冗长;需要STLSoft(仅标头);大多数/所有平台
  10. 安全(在单个语句中您不会使用多个int_to_string()调用),快速;需要STLSoft(仅标头);仅限 Windows
  11. 安全,但速度慢;需要Poco C++;大多数/所有平台

回答by Jeremy

In C++11, you can use std::to_string, e.g.:

在 C++11 中,您可以使用std::to_string,例如:

auto result = name + std::to_string( age );

回答by Jay Conrod

If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).

如果您有 Boost,则可以使用 将整数转换为字符串boost::lexical_cast<std::string>(age)

Another way is to use stringstreams:

另一种方法是使用字符串流:

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;

A third approach would be to use sprintfor snprintffrom the C library.

第三种方法是使用sprintfsnprintf来自 C 库。

char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;

Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.

其他海报建议使用itoa. 这不是标准功能,因此如果您使用它,您的代码将不可移植。有些编译器不支持它。

回答by Ben Hoffstein

#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();

回答by tloach

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.

http://www.research.att.com/~bs/bs_faq2.html无耻地被盗。

回答by Kevin

This is the easiest way:

这是最简单的方法:

string s = name + std::to_string(age);

回答by 0x499602D2

If you have C++11, you can use std::to_string.

如果你有 C++11,你可以使用std::to_string.

Example:

例子:

std::string name = "John";
int age = 21;

name += std::to_string(age);

std::cout << name;

Output:

输出:

John21

回答by user12576

It seems to me that the simplest answer is to use the sprintffunction:

在我看来,最简单的答案是使用sprintf函数:

sprintf(outString,"%s%d",name,age);

回答by Seb Rose

#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}

回答by Zing-

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

Then your usage would look something like this

然后你的用法看起来像这样

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled[and tested :p ]

谷歌搜索[并测试 :p ]