How to Store a Sentence in an Array in C++

Written by mike wallace
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Store a Sentence in an Array in C++
Understanding character strings is a fundamental building block in software development. (Jupiterimages/liquidlibrary/Getty Images)

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.

Skill level:
Moderately Easy

Things you need

  • C++ Compiler, such as GCC
  • C++ IDE, such as Eclipse CDT

Show MoreHide


  1. 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. 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. 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. 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";

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.