Using Arrays and File I/O

Tom Kelliher, CS17

May 6, 1996

Using Arrays

Example: Read positive integer values (at most 3) from the user and print them in reverse order. Use -1 as a sentinel value.

const int MAX = 3;
int data[MAX];
int count = 0;
int i;

cout << "? ";
cin >> data[count];

while (count < MAX && data[count] != -1)
{
   ++count;
   cout << "? ";
   cin >> data[count];
}

for (i = count - 1; i >= 0; --i)
   cout << data[i] << endl;

Importance of count.

Disk I/O

New include files and new variable types:

#include <fstream.h>

ifstream in;   // Input file variable type.
ofstream out;  // Output file variable type.

Difference between file name and file variable.

Important functions:

Example Program

/**********************************************************************
 * fileio.cc
 * Tom Kelliher
 *
 * This is a small program that demonstrates a number of things:
 *    o How to use an array as a function parameter.  Note that arrays
 *      are ALWAYS passed by reference.
 *    o How to use the getline() function with cin to read an entire
 *      line from cin.
 *    o How to use the open() and fail() functions with an ifstream
 *      variable (in).
 *    o How to read numbers from a disk file bound to an ifstream
 *      variable.
 *    o How to use eof() to test for reaching the end of a file.
 *    o How to use close() to close a file.
 **********************************************************************/


#include <fstream.h>
#include <iostream.h>


const int MAX = 100;   // Maximum number of data elements.
const int LINE = 80;   // Maximum length of a single keyboard input.


// Prototype.
int getInputs(int data[], int max);


/**********************************************************************
 * main()
 **********************************************************************/

int main()
{
   int d[MAX];   // The data.
   int count;    // How much data.
   int i;        // Index variable.

   count = getInputs(d, MAX);

   cout << "Read " << count << " items:\n";

   // Just print the data out.
   for (i = 0; i < count; ++i)
      cout << "Element " << i << ": " << d[i] << endl;

   return 0;
}


/**********************************************************************
 * getInputs() --- read integers from a file into an array.
 *
 * Preconditions: data is an int array with at least max elements.
 * Postconditions: After querying for the name of an input file and
 * opening the file, integers are read from the file into the array.
 * At most max elements are read.  The file is closed and the count of
 * numbers read is returned.
 **********************************************************************/

int getInputs(int data[], int max)
{
   int count = 0;   // How many numbers read?
   char name[LINE]; // Used to store the filename.
   ifstream in;     // Our file variable.

   // Get a filename and try to open the file.
   do
   {
      cout << "File name: ";
      cin.getline(name, LINE);

      in.open(name);
   } while (in.fail());

   // Read until we've filled the array or we reach end-of-file.
   while (count < max && !in.eof())
   {
      in >> data[count];
      ++count;
   }

   // If we reached eof, the count will be off by one.  Fix it.
   if (in.eof())
      --count;

   in.close();
   return count;
}

A Function for Writing an Array to a File

Again, must use #include <fstream.h>.

/**********************************************************************
 * putInputs() --- write integers from an array to a file.
 *
 * Preconditions: data is an int array with at least max elements.
 * Postconditions: After querying for the name of an output file and
 * opening the file, integers are written from the array to the file.
 * At most max elements are written.  The file is then closed.
 **********************************************************************/

void putInputs(int data[], int max)
{
   int count;       // How many numbers written
   char name[LINE]; // Used to store the filename.
   ofstream out;     // Our file variable.

   // Get a filename and try to open the file.
   do
   {
      cout << "File name: ";
      cin.getline(name, LINE);

      out.open(name);
   } while (out.fail());

   // Write until we've written the entire array.
   for (count = 0; count < max; ++count)
      out << data[count] << endl;

   out.close();
}

Sorting Data in an Array

Two sorting orders:

Many, many sorting ``algorithms.''

We'll use ascending ``bubble sort:''

Demonstration. Sort 10, 4, 6, 2.

Code:

void sort(int list[], int size);
void swap(int& a, int& b);


/**********************************************************************
 * sort --- Use bubble sort to sort an array of ints.
 *
 * Preconditions: list is an int array of at least size elements.
 * Postconditions: list is sorted in ascending order.
 **********************************************************************/

void sort(int list[], int size)
{
   int pass;   // Number of pass.
   int i;      // Index variable.

   // Do size - 1 passes.
   for (pass = 1; pass < size; ++pass)
      // On each pass, compare size - pass pairs of elements.
      for (i = 0; i < size - pass; ++i)
         if (list[i] > list[i + 1])
            swap(list[i], list[i + 1]);   // Swap if out of ascending
                                          // order.
}


/**********************************************************************
 * swap --- swap 2 ints.
 *
 * Preconditions: a and b are ints.
 * Postconditions: a's and b's values have been swapped.
 **********************************************************************/

void swap(int& a, int& b)
{
   int temp;

   temp = a;
   a = b;
   b = temp;
}



Thomas P. Kelliher
Sun May 5 17:37:25 EDT 1996
Tom Kelliher