C++ Program to Copy String

January 19, 2023, Learn eTutorial

How to copy string objects in C++?

Ask the user to enter a string. Read the string entered by the user to the string type variable str1. getline() function in C++ is used to read the string. We can simply copy the string object in the variable str1 to str2  by using the = assignment operator. Print both str1 and str2.

getline( string ) in C++

getline() is a standard library function in C++ and is used to read a string or a line from the input stream. It allows accepting and reading single and multiple line strings from the input stream. 

We can simply copy a string object in the variable to another variable by using the = assignment operator. eg : a = b;


Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare string type variables str1 and str2

Step 5: Ask the user to enter a string str1.

Step 6: Read the string into the variable str1

Step 7: Copy the string from str1 to str2 by using the assignment operator  ‘=’.

Step 8: print str1;

Step 9: print str2;

Step 10: Exit.

C++ Source Code

                                          #include <iostream>
using namespace std;

int main()
    string str1, str2;

    cout << "Enter string str1: ";
    getline (cin, str1);

    str2 = str1;

    cout << "str1 = "<< str1 << endl;
    cout << "str2 = "<< str2;

    return 0;


Enter string str1: welcome to learnetutorials
str1 = welcome to learnetutorials
str2 = welcome to learnetutorials