20-CS-122-001 Computer Science II Spring 2012
Read From File - Two Passes

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source

#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;

class String { 
public:
   string str; 
};

int main(int argc, char **argv) {
   string buffer;
   int count=0;

   // Print usage information if number of command line arguments is wrong
   if (argc != 2) { 
      cout << "\nUsage: " << argv[0] << " \n";
      exit(0);  
   }

   // Open the file and count the number of lines
   fstream *fin = new fstream(argv[1], ios::in);
   if (fin->fail()) {
      cerr << "Cannot open file " << argv[1] << "\n";
      exit(0);
   }

   while (getline(*fin, buffer)) count++;
   fin->close();
   fin->clear();

   // Allocate space for the Strings array
   //Strings strings[count];
   String **strings = new String*[count];

   // Open the file and copy the strings into the array
   fin->open(argv[1], ios::in);
   for (int i=0 ; i < count ; i++) {
      getline(*fin, buffer);
      (strings[i] = new String())->str = buffer;
   }
   fin->close();
   fin->clear();
   
   // Print the result
   for (int i=0 ; i < count ; i++)
      cout << "[" << strings[i]->str << "]\n";
   cout << "--------------------------\n";
}