How to Concatenate Strings in C++: Simple Syntax and Examples
In C++, you can concatenate strings using the
+ operator or the append() method of the std::string class. Both ways join two or more strings into one combined string.Syntax
There are two common ways to concatenate strings in C++:
string3 = string1 + string2;— uses the+operator to join strings.string1.append(string2);— addsstring2to the end ofstring1.
Both string1 and string2 must be std::string objects or convertible to strings.
cpp
std::string string1 = "Hello, "; std::string string2 = "World!"; // Using + operator std::string string3 = string1 + string2; // Using append method string1.append(string2);
Example
This example shows how to concatenate two strings using both the + operator and the append() method, then prints the results.
cpp
#include <iostream> #include <string> int main() { std::string greeting = "Hello, "; std::string name = "Alice!"; // Using + operator std::string message1 = greeting + name; std::cout << message1 << std::endl; // Using append method std::string message2 = greeting; message2.append(name); std::cout << message2 << std::endl; return 0; }
Output
Hello, Alice!
Hello, Alice!
Common Pitfalls
Common mistakes when concatenating strings in C++ include:
- Trying to use
+with C-style strings (char arrays) without converting tostd::string, which causes errors. - Modifying string literals directly, which is not allowed.
- Forgetting that
append()changes the original string, while+creates a new string.
cpp
#include <iostream> #include <string> int main() { const char* cstr1 = "Hello, "; const char* cstr2 = "World!"; // Wrong: cannot use + directly on C-style strings // std::string result = cstr1 + cstr2; // Error // Correct: convert to std::string first std::string result = std::string(cstr1) + std::string(cstr2); std::cout << result << std::endl; return 0; }
Output
Hello, World!
Quick Reference
Summary tips for string concatenation in C++:
- Use
+to create a new combined string. - Use
append()to add to an existing string. - Convert C-style strings to
std::stringbefore concatenation. - Remember string literals are immutable; always use
std::stringobjects.
Key Takeaways
Use the + operator or append() method to concatenate std::string objects in C++.
Convert C-style strings to std::string before concatenation to avoid errors.
append() modifies the original string, while + creates a new string.
Never try to modify string literals directly; use std::string instead.