C++ Program to Convert String to Array of Characters

Hello Everyone!

In this tutorial, we will learn how to demonstrate how to convert the given String into an Array of Characters, in the C++ programming language.

Logic:

This can be done by making use of the c_str() method.

Syntax:

 //This is an in-built method defined within the string.h library
    strncpy(cArray, s.c_str(), sizeof(cArray));

For a better understanding of its use case, please refer to the below code.

Code:

#include <iostream>

//This header file is used to make use of the strncpy() method
#include <string.h>

using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to convert a String to an array of characters  ===== \n\n";

    string s;

    cout << "\n\nEnter a String without any space : ";
    cin >> s;

    cout << "\n\nThe array containing the characters of the strings as it's element is: "
         << "\n\n";

    //The array of characters to be printed
    char cArray[1024];

    //This is an in-built method defined within the string.h library
    strncpy(cArray, s.c_str(), sizeof(cArray));

    //Initializing all the elements of the array to 0, all at once.
    cArray[sizeof(cArray) - 1] = 0;

    //declaring the loop variable within the loop is syntactically correct, but it's scope remains limited to the loop.
    for (int i = 0; cArray[i] != 0; i++)
    {
        cout << "\n cArray[ " << i << " ] :   " << cArray[i];
    }

    cout << "\n\n";

    return 0;
}

Output:

C++ string to char array

We hope that this post helped you develop a better understanding of the concept of converting the String into an array of char, in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )