Character Arrays


One of the most common uses of an array is a character array. A character array is simply a string of characters that makes up one or more words. It is common to place such input into arrays of characters. Let’s look at two examples.

Example 3.4

Step 1: Enter the following code into your favorite text editor.

#include <iostream> using namespace std; int main() {     char name[25];  cout << "Please enter your name \n";  cin >> name;  cout << "Hello " << name << endl; return 0;    }

Step 2: Compile and run the program. You should see something similar to what is shown in Figure 3.3.

click to expand
Figure 3.3: Character arrays.

This code is a rather straightforward and practical illustration of how to use arrays, specifically arrays of characters. There is only one problem. We declared the array to hold 25 characters. What happens if the user enters 30 characters? The answer is that your program may crash. However, there is a solution. In Chapter 2 you were introduced to the getline function and you were told that it was the safest way to input data into an array. Recall that the getline function specified what array to put the address in, and how many bytes to put in. If the user enters more data than that, then the extra characters are simply ignored.

Example 3.5

Step 1: Enter the following code into your favorite text editor.

#include <iostream> using namespace std; int main() {     char name[25];  cout << "Please enter your name \n";  cin.getline(name,25);  cout << "Hello " << name << endl;  return 0; }

Step 2: Compile and run the code. You should see something similar to Figure 3.4.

click to expand
Figure 3.4: Using getline with character arrays.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net