我原以为这很简单,但它出现了一些困难。如果我有

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

我如何结合他们得到一个单一的字符串“John21”?


当前回答

#include <sstream>

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

那么你的用法应该是这样的

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

谷歌[并测试:p]

其他回答

作为一行:name += std::to_string(年龄);

这是最简单的方法:

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

如果你想使用+来连接任何有输出操作符的东西,你可以提供一个操作符+的模板版本:

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

然后你可以用一种直接的方式来写你的连接:

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

输出:

the answer is 42

这不是最有效的方法,但你不需要最有效的方法,除非你在一个循环中做很多连接。

#include <sstream>

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

那么你的用法应该是这样的

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

谷歌[并测试:p]

这个问题可以用许多方法解决。我将以两种方式展示它:

Convert the number to string using to_string(i). Using string streams. Code: #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; }