Sorting an Array of Structs not working

This is a discussion on Sorting an Array of Structs not working within the C++ Programming forums, part of the General Programming Boards category; OKAY...I was hoping to finish this assignment without any more help but after 4 hours of trying to find my ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12

    Sorting an Array of Structs not working

    OKAY...I was hoping to finish this assignment without any more help but after 4 hours of trying to find my problem I have gave in.

    What I have is an Array of Structs that I need to sort, within the struct I have names stored in arrays and thats what I have to sort by, then I will have to change it to sort by the Enum within the struct as well but one thing at a time.
    I just need it to sort the list first.

    The prog reads information in from a file stores it in the Array of structs, prints the original list then sorts and prints the sorted list. Right now all it does it read store print original list and then prints the original list again unsorted. I cannot see where I have messed up so I am hoping a fresh set of eyes will see my error and let me know where it is and possibly what I have to do to correct it.

    Code:
    #include <string>
    #include <iostream>
    #include <cstring>
    #include <cassert>
    #include <fstream>
    using namespace std;
    
    enum year_in_school {freshman, sophomore, junior, senior, special};
    
    struct studentrec
    {
           char name[20];
           int age;
           float gpa;
           year_in_school classification;
    }; //End Struct
    
    istream &operator >>(istream &is, year_in_school &yr);
    istream &operator >>(istream &is, studentrec &r);
    ostream &operator <<(ostream &os, year_in_school yr);
    ostream &operator <<(ostream &os, const studentrec &r);
    bool operator <(studentrec st1, studentrec st2);
    template <class t> void sortlist(t list[], int count);
    
    int main(void)
    {
        studentrec stlist[17];
        int i;
        int stcount;
        ifstream fin;
        
       cout << "Enter the name of the input file: ";
        string inputFileName;
        getline(cin, inputFileName);
        
        fin.open(inputFileName.data()); // Filestream Open
        assert(fin.is_open());          // Check to make sure filestream is open
       
        for (i=0; i<=17; i++)
            fin >> stlist[i];           // Filestream reads into array of structs
                if (fin.eof() );    
        fin.close();                    // Filestream Closed
       
        cout << "\n\nOriginal List of Students" << endl;  //List before Sort
             for (i=0; i<17; i++)
                 cout << stlist[i];
        
        cout << "\n\nSorted List of Students" << endl;    // List after Sort
             sortlist (stlist, stcount);
             
             for (i=0; i<17; i++)
                 cout << stlist[i];
        
       system ("pause");
       return 0; 
    }//end Main
    
    
    istream &operator >>(istream &is, year_in_school &yr)
    {
        int year;
     
        is >> year;
    
        switch( year )
        {
            case freshman:
                yr = freshman;
                break;
            case sophomore:
                yr = sophomore;
                break;        
            case junior:
                yr = junior;
                break;
            case senior:
                yr = senior;
                break;
            case special:
                yr = special;
                break;
            default:
                 return (is);
                 break;
        };
        return( is );
    } // end Year Switch
    
    
    istream &operator >>(istream &is, studentrec &r)
    
    {
      int temp;
      char filler[80];
        
        is.get(r.name,20);
        if(is.eof())
           return is;
        is >> r.age >> r.gpa >> r.classification;
        is.getline(filler,80);
      return is;
    } //end Studentrec input
    
    
    ostream &operator <<(ostream &os, year_in_school yr)
    {
     switch(yr)
     {
      case freshman:  
           os << "Freshman";  
           break;
      case sophomore: 
           os << "Sophomore"; 
           break;
      case junior:    
           os << "Junior";    
           break;
      case senior:    
           os << "Senior";    
           break;
      case special:   
           os << "Special";   
           break;
      default:        
           os << "Unspecified" << endl; 
           break;
     }
     return  os;
    } //end year_in_school OS
    
    
    ostream &operator <<(ostream &os, const studentrec &r)
    {
        os << "          Name : " << r.name << endl;
        os << "           Age : " << r.age << endl;
        os << "           GPA : ";
        os.precision(4);
        os  << r.gpa << endl;
        os << "Classification : " << r.classification << endl;
        os << endl;
    
        return( os );
    }  //end print function
    
    
    bool operator <(studentrec st1, studentrec st2)
    {
        return (strcmp(st1.name, st2.name))<0;
    } //end "<" define
    
    
    template <class t> void sortlist(t list[], int count)
    {
      int minpos;
      int i;
      int pass;
      count--;
     
      for(pass=0; pass<count; pass++) 
           {
            minpos = pass;
            for(i=pass+1; i<=count; i++)  
                if (list[i] < list[minpos])
                    minpos = i;
            if(minpos != pass)
              swap(list[minpos], list[pass]);
           }
       return ;
    }  // End Sortlist
    Also here is the text file that it reads input in from called "students.txt"
    Code:
    Ericson, Josh                21 	3.513	3
    Sampson, Lee                 45         3.7	4
    Thompson, Jim                18		2.5	9
    Clark, James E.              21		3.75    1
    Johnson, John T.             20         1.75    0
    Bradley, Bill                19	        2.1     1
    Fitzgerald, Thomas           20         3.6     2
    Zircon, Zelda                49	        2.05    5
    Brown, Susan                 18         2.35    0
    Collin, Amanda               19         2.95    1
    Weatherington, Jane          37         1.95    5
    Bullington, John             23         3.516   4
    Limbaugh, Rush               55         0.75    5
    Cuomo, Mario                 71         2.98    5
    Ford, John                   17         0.00    0
    Bush, Maynard                18         2.65    1
    Maynard, Jill                22         3.15    3
    Also DEV-C++ will not recognize the "system("pause");" command now...Last night before I added the sort it was working fine would read store print and stop, now it just compiles, executes and exits the prog,all I see is the prog window flash up on the screen...I tried commenting out all the sort stuff to see if that was it but not no matter what it exits and never pauses...Any ideas on that...Other progs that I have with the pause command work fine...it will stop on those but not this one.

    Thanks in advance everyone.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,633
    Trace the stcount variable. You will find that you forgot to initialise it.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Code:
    studentrec stlist[17];
        
    ...
    
    for (i=0; i<=17; i++)
        fin >> stlist[i];
    That should be < 17 and not <= 17.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12
    Guys thanx for the debug...I must have stared at that code for more than 4 hours this morning...I never saw those mistakes...I corrected and it worked fine...Now the problem is that he wants us to sort the array of structs by the year_in_school classification.

    I changed this
    Code:
    bool operator <(studentrec st1, studentrec st2)
    {
        return (strcmp(st1.name, st2.name))<0;
    } //end "<" define
    to this
    Code:
    bool operator <(studentrec st1, studentrec st2)
    {
        return (strcmp(st1.classification, st2.classification))<0;
    } //end "<" define
    and I get this error
    In function `bool operator<(studentrec, studentrec)':
    154 cannot convert `year_in_school' to `const char*' for argument `1' to `int strcmp(const char*, const char*)'

    I dont understand the error and my teacher is not availible...What does the strcmp return so that the sort will work I guess is what is causing the error...I think it wants me to use a static cast to convert the Year_in_school to an int ...But I thought that ENUMs were ints...So I dont understand the error...

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,633
    In this case, you are comparing integral types. Do not use strcmp, instead just do a simple:
    return st1.classification < st2.classification;
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12
    Oh OK...So since I am comparing two ENUMs and they are represented by INTs I dont have to compare them simply see which is larger/smaller whatever than the other...OK...why didnt it just say that...

    Well I ran it and it almost worked...It sorted the list according to classification except for 2 of the records....
    Code:
    Zircon, Zelda                49	        2.05    5     
    Limbaugh, Rush               55         0.75    5
    were the first two names in the sorted list...Then it went down the list just like it should..
    What confuses me is that not only are both of them "Unspecified" but there are more than these two that are represented by a "5" in the classification input range...Any ideas???

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    What's your latest code?

    >> for(i=pass+1; i<=count; i++)
    Did you fix his problem where you should be using < instead of <=. Note that it also means that pass < count in your outer loop needs to be adjusted, too.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12
    My latest code is this
    Code:
    #include <string>
    #include <iostream>
    #include <cstring>
    #include <cassert>
    #include <fstream>
    using namespace std;
    
    enum year_in_school {freshman, sophomore, junior, senior, special};
    
    struct studentrec
    {
           char name[20];
           int age;
           float gpa;
           year_in_school classification;
    }; //End Struct
    
    istream &operator >>(istream &is, year_in_school &yr);
    istream &operator >>(istream &is, studentrec &r);
    ostream &operator <<(ostream &os, year_in_school yr);
    ostream &operator <<(ostream &os, const studentrec &r);
    bool operator <(studentrec st1, studentrec st2);
    template <class t> void sortlist(t list[], int count);
    
    int main(void)
    {
        studentrec stlist[17];
        int i;
        int stcount = 0;
        ifstream fin;
        
       cout << "\n\nEnter the name of the input file: ";
        string inputFileName;
        getline(cin, inputFileName);
        
        fin.open(inputFileName.data()); // Filestream Open
        assert(fin.is_open());          // Check to make sure filestream is open
       
        for (i=0; i<17; i++)
            fin >> stlist[i], stcount++;           // Filestream reads into array of structs
                if (fin.eof() );    
        fin.close();                    // Filestream Closed
       
        cout << "\n\n********Original List of Students********\n" << endl;  //List before Sort
             for (i=0; i<17; i++)
                 cout << stlist[i];
        
        cout << "\n\n\n\n********Sorted List of Students********\n" << endl;    // List after Sort
             sortlist (stlist, stcount);
             
             for (i=0; i<17; i++)
                 cout << stlist[i];
        
       system ("pause");
       return 0; 
    }//end Main
    
    
    istream &operator >>(istream &is, year_in_school &yr)
    {
        int year;
     
        is >> year;
    
        switch( year )
        {
            case 0:
                yr = freshman;
                break;
            case 1:
                yr = sophomore;
                break;        
            case 2:
                yr = junior;
                break;
            case 3:
                yr = senior;
                break;
            case 4:
                yr = special;
                break;
            default:
                 return (is);
                 break;
        };
        return( is );
    } // end Year Switch
    
    
    istream &operator >>(istream &is, studentrec &r)
    
    {
      int temp;
      char filler[80];
        
        is.get(r.name,20);
        if(is.eof())
           return is;
        is >> r.age >> r.gpa >> r.classification;
        is.getline(filler,80);
      return is;
    } //end Studentrec input
    
    
    ostream &operator <<(ostream &os, year_in_school yr)
    {
     switch(yr)
     {
      case freshman:  
           os << "Freshman";  
           break;
      case sophomore: 
           os << "Sophomore"; 
           break;
      case junior:    
           os << "Junior";    
           break;
      case senior:    
           os << "Senior";    
           break;
      case special:   
           os << "Special";   
           break;
      default:        
           os << "Unspecified" << endl; 
           break;
     }
     return  os;
    } //end year_in_school OS
    
    
    ostream &operator <<(ostream &os, const studentrec &r)
    {
        os << "          Name : " << r.name << endl;
        os << "           Age : " << r.age << endl;
        os << "           GPA : ";
        os.precision(3);
        os  << r.gpa << endl;
        os << "Classification : " << r.classification << endl;
        os << endl;
    
        return( os );
    }  //end print function
    
    
    bool operator <(studentrec st1, studentrec st2)
    {
        return st1.classification < st2.classification;
    } //end "<" define
    
    
    template <class t> void sortlist(t list[], int count)
    {
      int minpos;
      int i;
      int pass;
      count--;
     
      for(pass=0; pass<count; pass++) 
           {
            minpos = pass;
            for(i=pass; i<count; i++)  
                if (list[i] < list[minpos])
                    minpos = i;
            if(minpos != pass)
              swap(list[minpos], list[pass]);
           }
       return ;
    }  // End Sortlist
    The sorted list comes out like this
    Code:
    ********Sorted List of Students********
    
              Name : Zircon, Zelda      
               Age : 49
               GPA : 2.05
    Classification : Unspecified
    
    
              Name : Limbaugh, Rush     
               Age : 55
               GPA : 0.75
    Classification : Unspecified
    
    
              Name : Johnson, John T.   
               Age : 20
               GPA : 1.75
    Classification : Freshman
    
              Name : Brown, Susan       
               Age : 18
               GPA : 2.35
    Classification : Freshman
    
              Name : Ford, John         
               Age : 17
               GPA : 0
    Classification : Freshman
    
              Name : Bradley, Bill      
               Age : 19
               GPA : 2.1
    Classification : Sophomore
    
              Name : Clark, James E.    
               Age : 21
               GPA : 3.75
    Classification : Sophomore
    
              Name : Collin, Amanda     
               Age : 19
               GPA : 2.95
    Classification : Sophomore
    
              Name : Bush, Maynard      
               Age : 18
               GPA : 2.65
    Classification : Sophomore
    
              Name : Fitzgerald, Thomas 
               Age : 20
               GPA : 3.6
    Classification : Junior
    
              Name : Ericson, Josh      
               Age : 21
               GPA : 3.51
    Classification : Senior
    
              Name : Bullington, John   
               Age : 23
               GPA : 3.52
    Classification : Special
    
              Name : Sampson, Lee       
               Age : 45
               GPA : 3.7
    Classification : Special
    
              Name : Cuomo, Mario       
               Age : 71
               GPA : 2.98
    Classification : Unspecified
    
    
              Name : Weatherington, Jane
               Age : 37
               GPA : 1.95
    Classification : Unspecified
    
    
              Name : Thompson, Jim      
               Age : 18
               GPA : 2.5
    Classification : Unspecified
    
    
              Name : Maynard, Jill      
               Age : 22
               GPA : 3.15
    Classification : Senior
    Last edited by ashcan1979; 09-28-2006 at 02:35 PM.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12
    OK I took out the "count--" in the sort function and that made it run one more time and corrected the
    Maynard, Jill
    at the end so now all I have is the first two records not in place..I still cant find that problem

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    I didn't see the count-- in your original code. That code was actually probably ok. Sorry about that. I don't see what the actual issue is right now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 11:09 AM
  2. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  3. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  4. sorting an array of structs
    By jo_jo2222 in forum C++ Programming
    Replies: 2
    Last Post: 04-08-2002, 11:52 PM
  5. sorting an array of structs
    By singletrackmind in forum C++ Programming
    Replies: 8
    Last Post: 11-13-2001, 02:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21