Joining Two Strings In C++

Exercise:

Write a C++ program to concatenate (join) two strings.

Program 1: Concatenating String Objects

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    string str1, str2, ans;
    cout << "Insert string 1: ";
    getline (cin, str1);
    cout << "Insert string 2: ";
    getline (cin, str2);
    ans = str1 + str2;
    cout << "\nstring after joining both = "<< ans;
    return 0;
}

Click Here to View the Output:
Insert string 1: I learn coding
Insert string 2: from codeofcode.com
string after joining both = I learn coding from codeofcode.com
Click Here to View the Explanation:
  • Two strings are taken from the user: str1 and str2.
  • They are both added using the addition operand +.
  • The result is displayed on the screen.

Program 2: Concatenating C-Style Strings

Click Here to View the Solution:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char str1[30], str2[30] ;
    cout << "Insert string 1: ";
    cin.getline (str1 , 30);
    cout << "Insert string 2: ";
    cin.getline (str2 , 30);
    strcat(str1, str2);       
    // str1 += str2
    cout << "\nstring 1 = " << str1 << endl;
    cout << "string 2 = " << str2;
    return 0;
}
Click Here to View the Output:
Insert string 1: I learn programming
Insert string 2:  from codeofcode.com
string 1 = I learn programming from codeofcode.com
string 2 =  from codeofcode.com
Click Here to View the Explanation:
  • The code is similar to program 1.
  • The elements of the string are limited 30. Two strings are taken from the user.
  • Pre-defined function strcat () is used to add both the strings.
%d bloggers like this: