Convert String to Array of Characters

C++C++Beginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/BasicsGroup -.-> cpp/arrays("`Arrays`") subgraph Lab Skills cpp/variables -.-> lab-96182{{"`Convert String to Array of Characters`"}} cpp/data_types -.-> lab-96182{{"`Convert String to Array of Characters`"}} cpp/operators -.-> lab-96182{{"`Convert String to Array of Characters`"}} cpp/strings -.-> lab-96182{{"`Convert String to Array of Characters`"}} cpp/for_loop -.-> lab-96182{{"`Convert String to Array of Characters`"}} cpp/arrays -.-> lab-96182{{"`Convert String to Array of Characters`"}} end

Include Libraries and Define Namespace

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;

Declare Variables and Input String

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;
}

Create an Array of Characters from String

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));

Initialize Elements of Array to Zero

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;

Print Array Elements

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

Summary

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.

Other C++ Tutorials you may like