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

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;

typedef struct { int city1, city2, cost; } Cable;

int cmp (const void *a, const void *b) {
   if ((*(Cable**)a)->cost < (*(Cable**)b)->cost) return -1;
   if ((*(Cable**)a)->cost > (*(Cable**)b)->cost) return 1;
   return 0;
}

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;
   fin.open(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";

   // Sort
   qsort(cables, count, sizeof(Cable*), cmp);

   // Print the result
   for (int i=0 ; i < count ; i++) 
      cout << i << ":" << cables[i]->city1 << " "
	   << cables[i]->city2 << " "
	   << cables[i]->cost << "\n";
   cout << "--------------------------\n";
}