我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
在c++ 20中,你可以做到:
auto result = std::format("{}{}", name, age);
与此同时,你可以使用{fmt}库,std::format基于:
auto result = fmt::format("{}{}", name, age);
声明:我是{fmt}库和c++ 20 std::格式的作者。
其他回答
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
作为一个与Qt相关的问题,下面是如何使用Qt:
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
字符串变量现在有someIntVariable的值代替%1,someOtherIntVariable的值在结尾。
这个问题可以用许多方法解决。我将以两种方式展示它:
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; }
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));
您可以使用下面给出的简单技巧将int连接到string,但请注意,这仅适用于integer为个位数时。否则,向该字符串逐位添加整数。
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5