This post will discuss how to concatenate strings in C++.

1. Using std::ostringstream

A simple solution to concatenate strings is using the std::ostream::operator<< function. The following solution demonstrates this by applying the insertion operator << to an output stream.

Download  Run Code

2. Using string::append

To append additional strings at the end of an existing string, we can use the string::append member function. It can be used as follows:

Download  Run Code

3. Using Implicit concatenation

In C++, any adjacent strings are joined together into a single string by the compiler. This is known as the implicit string concatenation. The following C++ program demonstrates it:

Download  Run Code

4. Using string concat

Another common approach to concatenate multiple string objects together is using the concat (+) operator. Here’s how the code would look like:

Download  Run Code

 
C++14 allows to forms a string literal of the various type using std::literals::string_literals::operator""s. These operators are declared in the namespace std::literals::string_literals. For example, the following code combines the string literals with standard s-suffix.

Download  Run Code

5. Using std::format

Starting with C++20, we can use the formatting library that offers a safe and extensible alternative to the printf family of functions. To concatenate multiple strings, we can use the std::format defined in header <format>, as shown below:

Download Code

That’s all about concatenating strings in C++.