How to Make a String Into an Array of Chars in C++
C++ is a general-use programming language and is one of the most commonly used programming languages for a variety of applications. Converting types of data, such as strings and arrays, is dealt with explicitly in the language of C++ with the "=" operator and the "memcpy()" method. Converting a string to an array captures each character in a string of text and places each individual letter into its own "element" in the array. The elements are arranged in a sequential index for easy referencing.
Instructions
-
-
1
Create a string object using the format:
string aString("Enter string text here.");
-
2
Create a character array that has a number of elements equal to the length of the inputted string. Do this using the "size()" function. For example, if you've created a string called "aString" the code becomes:
char *array=new char[aString.size() + 1];
array[aString.size()]=0; -
3
Use the "memcpy()" and "c_str()" functions to read the string into the character array. For example:
memcpy(array,aString.c_str(),aString.size());
The final code snippet will look something like this:
string aString("Enter string text here.");
char *array=new char[aString.size() + 1];
array[aString.size()]=0;
memcpy(array,aString.c_str(),aString.size());
-
1
