How to Store a Sentence in an Array in C++
Learning how to manipulate character arrays is a fundamental step in learning how to program in a language. A character array is a sequence of memory locations that can store a sentence. C++ can store sentences just like the C language by using arrays. These arrays are usually called C-style strings. Every element of the array holds a single character and ends with a special character called a null terminator.
Instructions
-
-
1
Define an array of a size equal to the number of letters and spaces in your sentence, plus one. The extra space will hold the null terminator and is the program's way of keeping track of where a string ends. Suppose you wanted to store the phrase "Hello" in your array. This sentence is 5 characters long, so you would define an array of size 6 like this:
char sentence[6];
-
2
Place characters in the array by assigning one character to each memory location in the array. This can be done as follows:
sentence[0] ='H';
sentence[1] ='e';
sentence[2] ='l';
sentence[3] ='l';
sentence[4] ='o';
-
-
3
Terminate the sentence with a special character called a null terminator. The null terminator tells C++ where the sentence ends. Add this line to your code:
sentence[5] ='\0';
-
4
Write the following line to declare another string using another method. With this method, the string size is calculated for you and the null terminator is automatically added.
char sentence_method2[] = "Hello";
-
1
References
- Photo Credit Jupiterimages/liquidlibrary/Getty Images