20-CS-122-001 Computer Science II Spring 2012
Use qsort on an Array of Strings

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

Prev      Next      Lectures      Source

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

typedef struct { char str[100]; } Strings;

// For qsort - lexicographic order
int strCompare (const void *x, const void *y) {
   return strcmp((*(Strings *)x).str, (*(Strings *)y).str);
}

int main(int argc, char **argv) {
   char buffer[1024];
   int count=0;

   // Usage message if arguments do not match
   if (argc != 2) { 
      cout << "\nUsage: " << argv[0] << " \n";
      exit(0);  
   }

   // First count the number of lines in the file
   fstream fin(argv[1], ios::in);
   while (fin >> buffer) count++;
   fin.close();

   cout << "Count:" << count << "\n";

   // Then allocate enough space to contain data from those lines   
   Strings strings[count];

   // Reopen the file and copy the data into memory
   fstream gin(argv[1], ios::in);
   for (int i=0 ; i < count ; i++) gin >> strings[i].str;
   gin.close();
   
   // Print the contents of our array
   for (int i=0 ; i < count ; i++)
      cout << "[" << strings[i].str << "]\n";
   cout << "--------------------------\n";

   // Sort all the strings in lexicographical order
   qsort(strings, count, sizeof(Strings), strCompare);
   
   // Print the contents of our array - it is sorted now
   for (int i=0 ; i < count ; i++)
      cout << "[" << strings[i].str << "]\n";
   cout << "\n";
}


// Sample output:
//  [hello]
//  [Hello]
//  [finally]
//  [what]
//  [when]
//  [who]
//  [how]
//  [animal]
//  [vegetable]
//  [Place]
//  [picnic]
//  [Awful]
//  --------------------------
//  [Awful]
//  [Hello]
//  [Place]
//  [animal]
//  [finally]
//  [hello]
//  [how]
//  [picnic]
//  [vegetable]
//  [what]
//  [when]
//  [who]