如何连接std :: string和int?

Obe*_*ane 631 c++ int concatenation stdstring

我认为这很简单,但它存在一些困难.如果我有

std::string name = "John";
int age = 21;
Run Code Online (Sandbox Code Playgroud)

如何组合它们以获得单个字符串"John21"

Dan*_*nyT 1069

按字母顺序排列:

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);
Run Code Online (Sandbox Code Playgroud)
  1. 是安全的,但很慢; 需要Boost(仅限标题); 大多数/所有平台
  2. 是安全的,需要C++ 11(to_string()已经包含在内#include <string>)
  3. 安全,快速; 需要FastFormat,必须编译; 大多数/所有平台
  4. 安全,快速; 需要FastFormat,必须编译; 大多数/所有平台
  5. 安全,快速; 需要{fmt}库,它可以在仅头模式下编译或使用; 大多数/所有平台
  6. 安全,缓慢,冗长; 要求#include <sstream>(来自标准C++)
  7. 很脆弱(你必须提供足够大的缓冲区),快速,冗长; itoa()是非标准扩展,并不保证可用于所有平台
  8. 很脆弱(你必须提供足够大的缓冲区),快速,冗长; 什么都不需要(是标准的C++); 所有平台
  9. 很脆弱(你必须提供足够大的缓冲区),可能是最快的转换,冗长; 需要STLSoft(仅限标题); 大多数/所有平台
  10. safe-ish(你不要在一个语句中使用多个int_to_string()调用),fast; 需要STLSoft(仅限标题); 仅Windows
  11. 是安全的,但很慢; 需要Poco C++ ; 大多数/所有平台

  • 除了你提供的一个链接,你有什么基于你的表现评论? (13认同)
  • 如果您使用的是 Arduino,您还可以使用“String(number)”。 (4认同)
  • 一个答案几乎就是您的全部声誉!!幸运豆;)我认为8是标准C(当然也是C ++),但可能值得区分。 (2认同)
  • 我也会添加 snprintf 来代替 sprintf。 (2认同)

Jer*_*emy 253

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

auto result = name + std::to_string( age );
Run Code Online (Sandbox Code Playgroud)


Jay*_*rod 82

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

另一种方法是使用stringstreams:

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
Run Code Online (Sandbox Code Playgroud)

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

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

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


Ben*_*ein 75

#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();
Run Code Online (Sandbox Code Playgroud)

  • 这很棒,BYT头文件是sstream (2认同)

tlo*_*ach 50

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

http://www.research.att.com/~bs/bs_faq2.html无耻地窃取.


小智 30

这是最简单的方法:

string s = name + std::to_string(age);
Run Code Online (Sandbox Code Playgroud)

  • 这是一个后C++ 11解决方案! (7认同)

0x4*_*2D2 22

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

例:

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

name += std::to_string(age);

std::cout << name;
Run Code Online (Sandbox Code Playgroud)

输出:

John21
Run Code Online (Sandbox Code Playgroud)

  • 它将是`name + = std :: to_string(static_cast <long long>(age));`在VC++ 2010中,你可以看到[这里](http://stackoverflow.com/questions/10664699/stdto-string-更比实例的过载功能百搭的参数的) (2认同)

use*_*576 18

在我看来,最简单的答案是使用该sprintf功能:

sprintf(outString,"%s%d",name,age);
Run Code Online (Sandbox Code Playgroud)

  • 将std :: string传递给%s时,sprintf(char*,const char*,...)在某些版本的编译器上会失败.但并非所有(它是未定义的行为)并且它可能取决于字符串长度(SSO).请使用.c_str() (3认同)

Seb*_*ose 15

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


Zin*_*ng- 11

#include <sstream>

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

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

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;
Run Code Online (Sandbox Code Playgroud)

用Google搜索 [并测试:p]


小智 9

此问题可以通过多种方式解决。我将以两种方式展示它:

  1. 使用将数字转换为字符串to_string(i)

  2. 使用字符串流。

    码:

    #include <string>
    #include <sstream>
    #include <bits/stdc++.h>
    #include <iostream>
    using namespace std;
    
    int main() {
        string name = "John";
        int age = 21;
    
        string answer1 = "";
        // Method 1). string s1 = to_string(age).
    
        string s1=to_string(age); // Know the integer get converted into string
        // where as we know that concatenation can easily be done using '+' in C++
    
        answer1 = name + s1;
    
        cout << answer1 << endl;
    
        // Method 2). Using string streams
    
        ostringstream s2;
    
        s2 << age;
    
        string s3 = s2.str(); // The str() function will convert a number into a string
    
        string answer2 = "";  // For concatenation of strings.
    
        answer2 = name + s3;
    
        cout << answer2 << endl;
    
        return 0;
    }
    
    Run Code Online (Sandbox Code Playgroud)


vit*_*aut 8

在 C++20 中,您将能够执行以下操作:

auto result = std::format("{}{}", name, age);
Run Code Online (Sandbox Code Playgroud)

同时您可以使用{fmt} 库std::format基于:

auto result = fmt::format("{}{}", name, age);
Run Code Online (Sandbox Code Playgroud)

免责声明:我是 {fmt} 库和 C++20 的作者std::format


ant*_*dev 8

作为单行:name += std::to_string(age);


uck*_*man 7

如果您想+用于连接任何具有输出操作符的内容,您可以提供以下模板版本operator+:

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用一种简单的方式编写你的连接:

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;
Run Code Online (Sandbox Code Playgroud)

输出:

the answer is 42
Run Code Online (Sandbox Code Playgroud)

这不是最有效的方法,但除非你在循环中进行大量连接,否则不需要最有效的方法.

  • 如果我尝试添加整数或整数和双精度数,会调用此函数吗?我想知道这个解决方案是否会覆盖通常的添加...... (2认同)

bsr*_*uth 5

如果您使用的是MFC,则可以使用CString

CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
Run Code Online (Sandbox Code Playgroud)

托管C++也有一个 字符串格式化程序.


Tom*_*ter 2

常见答案:itoa()

这不好。 itoa是非标准的,正如此处指出的。

  • itoa 是非标准的:http://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux (2认同)