Copying Strings in C++

Exercise:

Write a C++ program to copy strings.

Program 1: String Objects

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    string str1, str2;
    cout << "Insert string 1: ";
    getline (cin, str1);
    str2 = str1;
    cout << "string 1 = "<< str1 << endl;
    cout << "string 2 = "<< str2;
    return 0;
}
Click Here to View the Output:
Insert string 1: i love programming
string 1 = i love programming
string 2 = i love programming
Click Here to View the Explanation:
  • The user is asked to enter a string object.
  • The string is put equal to another string. The string is copied to another variable. They are both printed on the screen.

Program 2: C Style Strings

Click Here to View the Solution:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char str1[30] , str2[30];
    cout << "Insert string 1: ";
    cin.getline (str1 , 30);
    strcpy(str2 , str1);
    cout << "string 1 = "<< str1 << endl;
    cout << "string 2 = "<< str2;
    return 0;
}
Click Here to View the Output:
Insert string 1: programming in c++
string 1 = programming in c++
string 2 = programming in c++
Click Here to View the Explanation:
  • The user is requested to enter string. It can contain up to 30 elements.
  • The strcopy() function is used to copy str1 to str2.
%d bloggers like this: