We will write a C++ Program to Copy Strings. Before that, you may go through the following topics in C++.
There are various ways to copy strings in C++. in this tutorial we will look at the following to copy strings.
- Using library function, strcpy()
- Without the use of strcpy() function
C++ Program to Copy Strings
The program takes user input for the string and then copy that string to another string in various ways shown below.
1. C++ Program to Copy Strings Using strcpy() Function
The strcpy()
function takes two arguments, first where it should be copied and second what should be copied and returns the copied value.
It is defined in string.h header file that needed to be included at the beginning of the program as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> #include <string.h> using namespace std; int main() { char str1[50], str2[50]; cout << "Enter the string: "; cin >> str1; // copy the string strcpy(str2, str1); cout << "Copied String (str2): " << str2; return 0; } |
Output:
Enter the string: simple2code
Copied String (str2): simple2code
2. C++ Program to Copy Strings without using strcpy() Function
Here we have used for loop instead of the library function. Also, you can perform the same operation using a while loop too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { char str1[50], str2[50]; int i; cout << "Enter the string: "; cin >> str1; // copy the string for (i = 0; str1[i] != '\0'; ++i) { str2[i] = str1[i]; } str2[i] = '\0'; cout << "Copied String (str2): " << str2; return 0; } |
Output:
Enter the string: John
Copied String (str2): John