C++ String Concatenation
Concatenation is a fancy word for joining strings together. In C++ you can glue words and sentences into a single larger string, which is perfect for building messages out of separate pieces.
Joining strings with +
The + operator, which adds numbers, also joins strings. When both operands are strings, C++ sticks the second string onto the end of the first and gives you one combined string.
Combining first and last name
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName << "\n"; // John Doe
return 0;
}Notice the " " in the middle. Without it you would get JohnDoe with no gap. You often need to add a space or punctuation between words when joining strings. You can also use += to append text to an existing string.
Appending with +=
#include <iostream>
#include <string>
using namespace std;
int main() {
string message = "Hello";
message += ", ";
message += "there!";
cout << message << "\n"; // Hello, there!
return 0;
}- + joins two strings into one
- += appends text to the end of an existing string
- Add " " yourself when you need a space between words
- You can chain several + operations in a single expression
Concatenation examples
Note: You cannot join two string literals directly with a number using +, for example "Age: " + 30 will not work as you expect. Convert the number first with to_string(30), or send each piece to cout separately.