Concatenating Strings

How Do I Concatenate Two Strings?

To concatenate two strings in C++, use std::string with the + operator, or += and append() to add to an existing one. Covers examples and common mistakes.

On this page
  1. Use + with two std::string values
  2. Add to an existing string with +=
  3. Use append() for the same job
  4. When one piece is a string literal
  5. Two C-style strings
  6. Check the length
  7. Joining numbers

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.

The complete guide to concatenating strings

How to Concatenate Strings in C++
Read the guide

Keep exploring

Guides from other topics

All topics →