Lab 7 - Arrays and C-Style Strings

Part I: Array "Index out of Bounds" demo

As discussed in class, C++ will happily let you use an invalid subscript to access memory that is not part of the array. The demo, array_example.cpp, shows how one can "clobber" other variables in the program by accessing an invalid subscript. Copy the file to your home directory using the command:
cp /home/fac/melissa/public_html/cs221-f09/array_example.cpp .
Compile and run the program using the following commands:
g++ -o demo array_example.cpp
./demo
You should see how the variables i and min get overwritten by using invalid subscripts for the array. This is why you, as the programmer, must keep track of the size of the array when accessing elements using the subscript operator.

Part II: Assignment

Name your code lab7.cpp. Email your completed code to me.

For this lab, you will create a small driver program that will read in a name and ID number and print them to the screen. The body of the driver loop will prompt the user for a name and use getline() to read the name. It will then prompt the user for an ID and use the extraction operator (the >> arrows) to read in the ID. It will then print out the name in a 20 character wide column and the ID in a 10 character wide column. You may use either printf() or iomanip to do the formatted output.

The driver program will continue to loop as long as the user enters a string that starts with "y" or "Y". This differs from Lab 6, where the driver program used only a single character to determine whether or not to continue. Since you will be reading a string AFTER using the extraction operator, you will need to use the ignore() function to clear any data left on the input stream by the extraction operator (which will be the '\n' character at minimum) before using getline() to read the user's response to the continue question.

You will also need to update the while condition for the driver loop since the response will now be a string instead of a single character. You will need to either use strncmp() or use the index operator to extract the first character of the string.

The pseudocode for your program is as follows:

do
  prompt the user for a name
  use getline() to read in the name
  prompt the user for an ID
  read the ID from the keyboard
  use formatted output to print the name and ID to the screen

  clear remaining data off the input stream
  prompt the user if they wish to continue
  use getline() to read their response
while response does not begin with "y" or "Y"
Note: You might find the following code handy for clearing excess characters from the stream when the user gives you a longer name than your string can hold: robust_input.cpp