20-CS-122-001 Computer Science II Spring 2012
Read From File - Two Passes, Three Numbers Per Line

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 Cable { 
public:
   int city1, city2, cost; 
};

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

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

   // Count the number of lines in the file
   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 contents of the file
   Cable **cables = new Cable*[count];

   // Copy the file lines into the Strings array - allocate space for
   // each line as needed
   fin->open(argv[1], ios::in);
   for (int i=0 ; i < count ; i++) {
      cables[i] = new Cable();
      *fin >> cables[i]->city1 >> cables[i]->city2 >> cables[i]->cost;
   }
   fin->close();
   fin->clear();
   
   // Print the result
   for (int i=0 ; i < count ; i++) 
      cout << i << ":" << cables[i]->city1 << " "
	   << cables[i]->city2 << " "
	   << cables[i]->cost << "\n";
   cout << "--------------------------\n";
}