← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 9 of 15

C++ String Concatenation

std::string supports concatenation with the + and += operators, letting strings and even individual characters be joined together directly without calling a special function.

Concatenating with +

The + operator, overloaded for std::string, joins two strings together into a new combined string, working just as naturally as adding two numbers.

Example: Concatenating with +

cpp
#include <iostream>
#include <string>

int main() {
	std::string first = "Hello, ";
	std::string second = "world!";
	std::string result = first + second;
	std::cout << result << std::endl;
	return 0;
}

Concatenating with +=

The += operator appends one string onto the end of another in place, modifying the original string variable rather than creating a brand new one.

Example: Concatenating with +=

cpp
#include <iostream>
#include <string>

int main() {
	std::string message = "Hello";
	message += ", world!";
	std::cout << message << std::endl;
	return 0;
}

Concatenating Multiple Strings

Several strings and literals can be chained together with + in a single expression, and C++ evaluates the concatenation left to right, building up the final combined string.

Example: Concatenating Multiple Strings

cpp
#include <iostream>
#include <string>

int main() {
	std::string result = "A" + std::string("B") + "C" + "D";
	std::cout << result << std::endl;
	return 0;
}

Appending Characters

A single char can be appended to a std::string with += just like another string, letting characters be built up one at a time inside a loop.

Example: Appending Characters

cpp
#include <iostream>
#include <string>

int main() {
	std::string word = "";
	word += 'H';
	word += 'i';
	std::cout << word << std::endl;
	return 0;
}

Mixing Strings and Non-String Values

The + operator cannot directly concatenate a std::string with a raw number; the number must first be converted to a string, commonly with std::to_string, before it can be joined in.

Example: Mixing Strings and Non-String Values

cpp
#include <iostream>
#include <string>

int main() {
	int age = 25;
	std::string message = "Age: " + std::to_string(age);
	std::cout << message << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.