In this tutorial you will learn about the C++ Program to Copy String and its application with practical example.
C++ Program to Copy String
In this tutorial, we will learn to create a C++ program that will Copy String in C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- Using Strings in C++ Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Add a string to the variable 3. Copy from the taken variable. 4. Printing the result string. 5. End |
Program to Copy String
As we all know the String is a collection of characters, symbols, digits, and blank spaces. In strings, only one variable is declared which can store multiple values. First will take the input string from the user. And then will copy the string. The C++ programming language has many pre-defined functions for string manipulation. but in today’s tutorial, we will do copy work with the help of a simple assignment operator without using a predefined function.
With the help of the below program, we can Copy String.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* C++ Program to copy a string. */ #include <iostream> using namespace std; int main() { //declaring the variables for the program to hold the string values string s1, s2; // taking input string rom the user cout << "Enter string s1: "; //reading the input from the user for program getline (cin, s1); //copy the string from one s2 = s1; //printing output for the string copy cout << "s1 = "<< s1 << endl; // printing the string 2 cout << "s2 = "<< s2; return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- s1 = it will hold the string value.
- s2 = it will hold the string value.
Taking Input string from the user for copying the string.
Reading the input string from the user with getline statement.
Copying the string with the help of the assignment operator.
Printing the output copied string2.