Concatenate Two Strings in C++

0

In this example of concatenation of two strings, the user will be asked to enter two strings and then they will be attached with each other and stored in a new string variable.

#include <iostream>
using namespace std;

int main() 
{
    string str1, str2, result;
    
    cout << "Please enter the string 1: ";
    getline(cin, str1);
    
    cout << "Please enter the string 2: ";
    getline(cin, str2);
    
    result = str1 + str2;
    
    cout << "Result: " << result;
    return 0;
}

Firstly, three string variables will be declared namely str1, str2 and result. The first string asked from the user will be stored in the str1 variable. The second string will then be stored in str2 variable.

   
 result = str1 + str2;




Next, another string variable result will be used to store the concatenation of two strings (str1 and str2). For concatenation the “+” operator is used. More than two strings can also be concatenated with each other using “+” operator. One important thing to remember is that the concatenated strings can only be stored in a string variable.

Output

Please enter the string 1: Welcome
Please enter the string 2:  James
Result: Welcome James

LEAVE A REPLY

Please enter your comment!
Please enter your name here