C++ Program to Concatenate two C-Style 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.

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.


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!
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn