In this post we will write a simple C++ program to concatenate two strings using Pointer, the code is self explanatory with comments for better understanding.
Write a C++ program to concatenate two Strings using Pointer:
You can also execute this code on our online compiler.
#include <iostream> using namespace std; int main() { char str1[100], str2[100]; char * s1 = str1; char * s2 = str2; // Inputting 2 strings from user cout<<"Enter 1st string: "; cin>>str1; cout<<"Enter 2nd string: "; cin>>str2; // Moving till the end of str1 while(*(++s1)); // Coping str2 to str1 while(*(s1++) = *(s2++)); cout<<"Concatenated string:"<<str1; return 0; }
Output:
Enter 1st string: Hello Enter 2nd string: Proprogramming Concatenated string: HelloProprogramming