Signup/Sign In

C++ Program To Copy One String To Another

In this example, you will learn to copy strings (both string objects and C-style strings).

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

Program To Copy One String To Another

#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;
}


Enter string s1: C++ Strings
s1 = C++ Strings
s2 = 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;
}


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



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.