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

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

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


当前回答

std:: ostringstream

<sstream>#include std::ostringstream s; 与<<“约翰”<<年龄; std::string query(s.str());

std:: to_string (C + + 11)

std::string查询("John " + std::to_string(年龄));

boost:: lexical_cast

# include <刺激/ lexical_cast.hpp > std::string查询("John " + boost::lexical_cast<std::string>(age));

其他回答

std:: ostringstream

<sstream>#include std::ostringstream s; 与<<“约翰”<<年龄; std::string query(s.str());

std:: to_string (C + + 11)

std::string查询("John " + std::to_string(年龄));

boost:: lexical_cast

# include <刺激/ lexical_cast.hpp > std::string查询("John " + boost::lexical_cast<std::string>(age));

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

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; }

你可以像这样使用C函数itoa():

    char buf[3];
    itoa(age, buf, 10);
    name += buf;

您可以使用下面给出的简单技巧将int连接到string,但请注意,这仅适用于integer为个位数时。否则,向该字符串逐位添加整数。

string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;

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