20-CS-122-001 Computer Science II Spring 2012
Read From File - One Pass

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; 
};

#define MAX_SIZE 100  // Not good!!

int main(int argc, char **argv) {
   int count=0;
   
   if (argc != 2) { 
      cout << "\nUsage: " << argv[0] << " \n";
      exit(0);  
   }

   String **strings = new String*[MAX_SIZE];

   fstream *fin = new fstream(argv[1], ios::in);
   if (fin->fail()) {
      cerr << "Cannot open file " << argv[1] << "\n";
      exit(0);
   }
   while (count < MAX_SIZE && *fin >> (strings[count++] = new String())->str);
   fin->close();
   
   // Print the result
   for (int i=0 ; i < count-1 ; i++)
      cout << "[" << strings[i]->str << "]\n";
   cout << "----------------------------------\n";
}