Introduction
In this lab, you will learn how to copy strings in C++. We will be using both string objects and C-style strings to demonstrate this.
In this lab, you will learn how to copy strings in C++. We will be using both string objects and C-style strings to demonstrate this.
Navigate to the ~/project
directory and create a new C++ file named main.cpp
.
cd ~/project
touch main.cpp
We can use the assignment operator to copy one string object to another. Follow the code below:
#include <iostream>
#include <string>
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;
}
Explanation:
iostream
and string
.s1
and s2
getline()
function which reads the entire string with space included.Code output
Enter string s1: Hello World!
s1 = Hello World!
s2 = Hello World!
We will be using strcpy()
function from cstring
library to copy C-style strings. Follow the code below:
#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;
}
Explanation:
iostream
and cstring
s1
and s2
getline()
function is not used in this instance because it is only used for string objects and not C-style strings. Instead, we use cin.getline
where the first argument is the array variable, and the second argument is the maximum size of the array to be read.strcpy()
function in cstring
Code output
Enter string s1: Hello World!
s1 = Hello World!
s2 = Hello World!
To run the code in the terminal, open the terminal in the project folder and execute the following commands:
g++ main.cpp -o main
./main
This command will compile the main.cpp
file and outputs an executable file named main
in the same directory. The second command runs the main
file and outputs the result in the terminal.
This lab discussed how to copy strings in C++ using string objects and C-style strings. You leant that for string objects, you can use the assignment operator and for C-style strings, you can use the strcpy()
function in cstring
. By following these simple steps, you can easily copy strings in C++.