Using getline for Stream Input

#include <iostream.h>   // cin/cout
#include <fstream.h>    // ifstream
#include <assert.h>     // assert()

const int MAXCHARS = 80;  // length of lines in file

void main(void)
{
  char myString[MAXCHARS + 1];
  ifstream inFile;
  ofstream outFile;

  // open input file
  inFile.open("datafile.in", ios::in);
  assert( !inFile.fail() );

  // open output file
  outFile.open("datafile.out", ios::out);
  assert( !outFile.fail() );

  // prime while loop (read one line from file)
  inFile.getline(myString, MAXCHARS);

  // while there is more data in the input file
  while ( !inFile.eof() )
  {
     // write the line to the output file
     outFile << myString << endl;

     // get next line from input file
     inFile.getline(myString, MAXCHARS);
  }

  inFile.close();    // close input file
  outFile.close();   // close output file
}
Note: This input technique is also called buffered input

Previous page
Next page

Back to Lesson 13 Index
Back to Outline