C++ Program to Concatenate Two Strings

To understand this example, you should have the knowledge of the following C++ programming topics:


You can concatenate two string objects in C++ using + operator.


Example 1: Concatenate String Objects

#include <iostream>
using namespace std;

int main()
{
    string s1, s2, result;

    cout << "Enter string s1: ";
    getline (cin, s1);

    cout << "Enter string s2: ";
    getline (cin, s2);

    result = s1 + s2;

    cout << "Resultant String = "<< result;

    return 0;
}

Output

Enter string s1: C++ Programming
Enter string s2:  is awesome.
Resultant String = C++ Programming is awesome.

You can concatenate two C-style strings in C++ using strcat() function.


Example 2: Concatenate C-style Strings

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char s1[50], s2[50];

    cout << "Enter string s1: ";
    cin.getline(s1, 50);

    cout << "Enter string s2: ";
    cin.getline(s2, 50);

    strcat(s1, s2); 

    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2;

    return 0;
}

Output

Enter string s1: I love        
Enter string s2:  C++ programming 
s1 = I love C++ programming
s2 =  C++ programming

Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to concatenate two strings.

  • Concatenate and return the two input strings str1 and str2.
  • For example, if str1 = "Hello, " and str2 = "World!", the return value should be "Hello, World!".
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges