C++ String Concatenation

C++ Tutorial

💻 C++ String Concatenation

String concatenation in C++ means joining two or more strings to form a single string.
C++ provides multiple safe and easy ways to do this.


1️⃣ Using + Operator ⭐ (Most Common)

Example


 

Output

Hello World

📌 Works only with string type, not char.


2️⃣ Using append() Function ⭐⭐

Example


 

Output

Good Morning

📌 Modifies the original string (s1).


3️⃣ Concatenating String with Variables ⭐⭐


 

Output

Age is 20

📌 Use to_string() to convert numbers into string.


4️⃣ Concatenating Multiple Strings ⭐⭐


 

Output

C++ is awesome

5️⃣ Using += Operator ⭐⭐


 

Output

Hello C++

📌 Efficient and clean for step-by-step joining.


6️⃣ Concatenating User Input Strings ⭐⭐


 

Input

Sanjit
Sinha

Output

Sanjit Sinha

7️⃣ ❌ Invalid String Concatenation (Common Mistake)

string s = "Hello";
int x = 10;
cout << s + x; // ❌ error

✔ Correct way:

cout << s + to_string(x);

8️⃣ string vs char Concatenation ⚠️

char a = 'A';
char b = 'B';
// cout << a + b; // ❌ adds ASCII values

✔ Correct:

string s;
s.push_back(a);
s.push_back(b);
cout << s;

Output

AB

📌 Interview Questions (String Concatenation)

Q1. Which operator is used for string concatenation?
👉 +

Q2. Can we concatenate string with integer directly?
👉 No (use to_string())

Q3. Difference between + and append()?
👉 + creates new string, append() modifies existing one


✅ Summary

✔ Use + for simple concatenation
✔ Use append() for modifying strings
✔ Use += for efficiency
✔ Convert numbers using to_string()
✔ Avoid mixing char and string directly

You may also like...