C++ Program to Copy Strings

To understand this example, you should have the knowledge of the following C++ programming topics:


You can simply copy string objects in C++ using = assignment operator.


Example 1: Copy String Object

#include <iostream>
using namespace std;

int main()
{
    string s1, s2;

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

    s2 = s1;

    cout << "s1 = "<< s1 << endl;
    cout << "s2 = "<< s2;

    return 0;
}

Output

Enter string s1: C++ Strings
s1 = C++ Strings
s2 = C++ Strings

To copy c-strings in C++, strcpy() function is used.


Example 1: Copy C-Strings

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char s1[100], s2[100];

    cout << "Enter string s1: ";
    cin.getline(s1, 100);

    strcpy(s2, s1);

    cout << "s1 = "<< s1 << endl;
    cout << "s2 = "<< s2;

    return 0;
}

Output

Enter string s1: C-Strings
s1 = C-Strings
s2 = C-Strings

Also Read:

Did you find this article helpful?