C++ for Beginners: C++ Program to Concatenate Two Strings

Hits: 7

(C++ programming Example for Beginners)

C++ Program to Concatenate Two Strings

In this example, you will learn to concatenate (join) two strings (both string objects and C-style strings).


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], result[100];

    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

 

C++ for Beginners: C++ Program to Concatenate Two Strings

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.