Introduction
In this lab, we will demonstrate how to convert a string into an array of characters in C++. The c_str()
method defined within the string.h
library is used to convert the string to an array of characters.
In this lab, we will demonstrate how to convert a string into an array of characters in C++. The c_str()
method defined within the string.h
library is used to convert the string to an array of characters.
We will create a new file named main.cpp
in the ~/project
directory using the following command:
touch ~/project/main.cpp
First, we need to include the necessary header files and define the std
namespace which we will be using.
#include <iostream>
#include <string.h>
using namespace std;
We declare a string
variable and ask the user to input a string without any space.
int main()
{
string s;
cout << "Enter a string without any space: ";
cin >> s;
}
We create an array of characters from the input string using the strncpy
function. The sizeof
operator is used to determine the size of the array.
char cArray[1024];
strncpy(cArray, s.c_str(), sizeof(cArray));
To avoid garbage values in the array, we initialize all the elements of the array to zero using the following statement.
cArray[sizeof(cArray) - 1] = 0;
We then loop through the array to print all the elements.
for (int i = 0; cArray[i] != 0; i++)
{
cout << "cArray[ " << i << " ]: " << cArray[i] << endl;
}
To compile and run the code, use the following command in the terminal:
g++ main.cpp -o main && ./main
In this lab, we learned how to convert a string to an array of characters in C++. The c_str()
method is used to create an array of characters from the input string. We initialized all elements of the array to zero and then looped through the array to print all its elements.