I'm supposed to a data file and Insert sort at the same time. the insertion must be in an empty array. I'm having trouble the Insert sort. It seems that the function is reading, but not sorting. can anyone tell what is going wrong?
here is my code, Thank you in advance.
#include <string.h>
#include <iostream>
#include <iomanip>
#include <fstream>
usingnamespace std;
intconst MAXSIZE = 100; // maximum number of records in total
intconst MAXLENGTH = 31; // maximum string length
intconst MAXGRADE = 100; // highest possible grade
intconst LOWGRADE = 0; // lowest possible grade
struct StudentType { // information of one student
int grade; // the grade of the person
char last[MAXLENGTH]; // last name (MAXLENGTH-1 at most)
char first[MAXLENGTH]; // first name (MAXLENGTH-1 at most)
};
// prototypes:
bool sortInput(istream&, StudentType [], int&);
void printList(const StudentType [], int);
//------------------------------- main ----------------------------------------
int main()
{
StudentType students[MAXSIZE]; // list of max of MAXSIZE number of students
int size = 0; // total number of students
// creates file object and opens the data file
ifstream infile("data1.txt");
if (!infile)
{
cout << "File could not be opened." << endl;
return 1;
}
// read and sort input by last then first name
bool successfulRead = sortInput(infile, students, size);
if (successfulRead)
{
printList(students, size);
}
return 0;
}
// ----------------------------------------------------------------------------
// functions:
/*name and grade are read into a temporary location.
loopes are from the end of the filled part of the array down to the beginning*/
// read and insert sort in one function.
bool sortInput(istream& infile, StudentType students[], int& size)
{
int count2 = 0;
StudentType temp;
while (size < MAXSIZE && !infile.eof())
{
infile >> temp.last >> temp.first >> temp.grade;
students[size] = temp;
size++;
for (count2 = size-1; count2 > 0 ; count2--)
{
if(strcmp(students[count2].last, temp.last) > 0)
students[count2+1] = students[count2];
elseif(strcmp(students[count2].last, temp.last) == 0 && strcmp(students[count2].first, temp.first) > 0)
students[count2+1] = students[count2];
elsebreak;
students[count2] = temp;
}
}
returntrue;
}
void printList(const StudentType students[], int size)
{
for (int i=0; i <= size; i++)
cout << setw(4) << students[i].grade
<< " " << students[i].last
<< " " << students[i].first << endl;
}