Use + with two std::string values
Put both pieces in std::string variables, then join them with +:
#include <iostream>
#include <string>
int main() {
std::string first = "Good ";
std::string second = "morning";
std::string greeting = first + second;
std::cout << greeting << '\n'; // Good morning
}
The + operator returns a new string. first and second keep their values.
Add to an existing string with +=
+= changes the string on its left side, so it is useful when you already have a string to extend:
std::string greeting = "Good ";
greeting += "morning"; // "Good morning"
+= also accepts a single character, so greeting += '!'; adds an exclamation mark.
Use append() for the same job
append() is a member function that does the same thing:
std::string greeting = "Good ";
greeting.append("morning"); // "Good morning"
append() returns a reference to the string, so calls can be chained.
When one piece is a string literal
At least one side of + must be a std::string. Both of these forms work:
std::string a = std::string("Good ") + "morning";
std::string b = "Good " + std::string("morning");
The expression "Good " + "morning" does not compile, because neither side is a std::string. For more on why, see how to concatenate strings in c.
Two C-style strings
A char array can be extended with std::strcat, as long as the array has room for the whole result plus the null character:
#include <cstring>
#include <iostream>
int main() {
char greeting[32] = "Good ";
std::strcat(greeting, "morning");
std::cout << greeting << '\n'; // Good morning
}
std::strcat does not check the size of the array, so keep the destination large enough.
Check the length
size() reports how many characters a std::string holds after the join. "Good " has 5 characters and "morning" has 7, so the joined string has 12:
std::cout << greeting.size() << '\n'; // 12
For other member functions you can call on a std::string, see c string methods.
Joining numbers
A number must become text before you join it. Use std::to_string:
int count = 3;
std::string label = "Items: " + std::to_string(count); // "Items: 3"
For other ways to make that conversion, see c convert int to string.