C++ Program to Concatenate Two Strings

«
»

This is a C++ Program to Concatenate two C-Style strings.

Problem Description

The program takes two strings and concatenates them, as in links them together.

Problem Solution

1. The program takes two strings initially.
2. Using string function, the two strings are concatenated.
3. The concatenated string is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Concatenate Two Strings. The program output is shown below.

  1. #include <iostream>
  2. #include <string.h>
  3. using namespace std;
  4. int main ()
  5. {
  6.     char str1[50], str2[50];
  7.     cout << "Enter string 1 : ";
  8.     gets(str1);
  9.     cout << "Enter string 2 : ";
  10.     gets(str2);
  11.     strcat(str1, str2);
  12.     cout << "Concatenated String : " << str1;
  13.     return 0;
  14. }
Program Explanation

1. The user is asked to enter two strings. They are stored in the character variables ‘str1′ and str2’.
2. Using ‘strcat()’, which is an inbuilt function under the library ‘string.h’, the two strings are concatenated.
3. The concatenated string is stored in str1.
4. The result is then printed.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter string 1 : Hello
Enter string 2 :  World
Concatenated String : Hello World
 
Case 2 :
Enter string 1 : 24
Enter string 2 : 68
Concatenated String : 2468
 
Case 3 :
Enter string 1 : C++
Enter string 2 : Programming
Concatenated String : C++Programming

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.