Return to Topic Menu | Computer Science Main Page | MathBits.com  | Terms of Use | Resource CD

 

SAMPLE PROGRAM:

/* Using a while loop to read integers from the keyboard and write them to a file until a sentinel is encountered */

#include<iostream.h>
#include<assert.h>                // needed to detect file errors
#include<fstream.h>             // necessary for file I/O

int main(void)
{
   int data;
   ofstream fout;
   const int SENTINEL = - 999;    //establishing the "guard's" value

    fout.open("numbers.dat", ios :: out);         //attempting to open file
    assert(! fout.fail( ));                                     //to detect errors in opening

    cout << "Enter an integer (-999 to end input): ";            //priming the loop
    cin >> data;
 
   while (data != SENTINEL)
   {
      fout << data << " ";
      cout << "Enter an integer (-999 to end input): ";
      cin >> data;
    }

    fout.close( );                               //close the output file
    assert(! fout.fail( ));                   //to detect errors in closing

    return 0;
}