Lab 7 - Arrays, File I/O and Formatting Output

Index out of bounds demo

Copy this file, array_example.cpp, to your current directory with the command:
cp /usr/users/mdanfor/public_html/cs221-f06/array_example.cpp .
Compile and run the program. Notice that by accessing an index that is out of bounds of the array, we have overwritten the contents of other variables in the program. This is why you must keep track of how many elements you have allocated to the array (the max_size variable in the code given in class). C/C++ will happily let you access indexes that are not part of the array. It is up to the programmer to prevent that.

Problems

Name your programs lab7_<problem>.cpp. Email your files to my Helios account.
  1. Download this example file to your account: lab7.dat. When you are logged into Helios, you use the following command to copy the file to your current directory:
    cp /usr/users/mdanfor/public_html/cs221-f06/lab7.dat .
    Write a program to read in the data from this file and store it in arrays. Note that the file has an integer followed by a double. You will need two arrays, one for integers and one for doubles, to store this data. The read from file get_input() code from Monday's lecture will need to be modified slightly to read both an integer and a double and then assign each to their corresponding array. After you have read in the data, print the contents of each array to the screen. Do not use cout in your get_input() function. Use a for() loop to step through each array, printing out each element, after you have read in all the data using get_input().
  2. Look at this example of formatted output created with the following program using cout: lab7_2.cpp
    integer output
    right justify: |         5|
     left justify: |5         |
    
    double output (2 precision)
    right justify: |      5.50|
     left justify: |5.50      |
    
    A small table without borders:
    Name      Integer   Double
    Alice              5      6.20
    Bob                8     13.34
    Carol             12     19.00
    
    Write a program that will replicate this output using printf(). You should be able to use one printf() command per line of output. Refer to Lab 5 for how to use printf(). Compare your program to the cout style of formatting used in lab7_2.cpp.