hello!
I badly need to submit this program within an hour from now so any help out there who could help debug my code, i would really appreciate it. there's something wrong with my qsort() syntax but i can't figure out what . spent 5 hours trying every possible ways for it but got no luck.
PLS HELP ME!!!
Here's the code:
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#define DESIRED_HEIGHT 180 //Polly's desired height in cm
#define DESIRED_WEIGHT 75 //Polly's desired weight in kg
using namespace std;
int compare_suitor();
struct suitorData{
char firstName[30]; //maximum length of suitor's firstname
char lastName[30]; //maximum length of suitor's lastname
int height;
int weight;
};
int main(){
int i;
int height=0;
int weight=0;
int numberOfSuitors=0;
char firstName[30];
char lastName[30];
ifstream inSuitorFile("suitors.txt", ios::in);
if(!inSuitorFile){
cerr<<"File could not be opened!";
exit(1);
}
suitorData suitor[20]; //maximum number of suitors
while(inSuitorFile>>suitor[numberOfSuitors].firstName>>suitor[numberOfSuitors].lastName>>
suitor[numberOfSuitors].height>>suitor[numberOfSuitors].weight){
cout<<lastName<<","<<" "<<firstName <<" "<<height <<" "<<weight <<endl;
suitor[numberOfSuitors].height = abs(height - DESIRED_HEIGHT);
if (weight > DESIRED_WEIGHT)
suitor[numberOfSuitors].weight = weight - DESIRED_WEIGHT;
else
suitor[numberOfSuitors].weight = - weight;
numberOfSuitors ++;
}
//qsort(reinterpret_cast<char*>(suitor), numberOfSuitors,
//sizeof(suitorData ), compare_suitor());
qsort(suitor, numberOfSuitors, sizeof(suitorData), compare_suitor); //either of the two isn't working... what's wrong?!?
for (i=0; i<numberOfSuitors; i++){
cout<<suitor[i].lastName, suitor[i].firstName);
}
system("pause");
return 0;
}
int compare_suitor(suitorData *a, suitorData *b)
{
int result; //result of comparsion
if (a->height < b->height)
return(-1);
if (a->height > b->height)
return(1);
if (a->weight < b->weight)
return(-1);
if (a->weight > b->weight)
return(1);
if ((result=strcmp(a->lastName,b->lastName)) != 0)
return result;
return(strcmp(a->firstName,b->firstName));
}
ps. you need to create a file 'suitors.txt' for it to work. (data firstnames, surnames, height and weight)
thanks!