This program reads in a file of names and displays them on the screen in reverse order.
#include <iostream.h> // cin/cout
#include <fstream.h> // ifstream
#include <assert.h> // assert()
#include <string.h> // strcpy()
const int MAXWORDS = 20; // max words in file
const int MAXLENGTH = 30; // max length of a word
void main(void)
{
char studentNames[MAXWORDS + 1][MAXLENGTH + 1];
char name[MAXLENGTH + 1];
int count = 0;
ifstream inFile;
// open input file
inFile.open("students.dat", ios::in);
assert( !inFile.fail() );
// prime while loop (read one line from file)
inFile.getline(name, MAXLENGTH);
// while there is more data in the input file
while ( !inFile.eof() )
{
// copy name into next string
strcpy(studentNames[count], name);
// increment our counter
count++;
// get another name from the file
inFile.getline(name, MAXLENGTH);
}
inFile.close(); // close input file
// print out the names in reverse
for (int i = count - 1; i >= 0; i--)
cout << studentNames[i] << endl;
}