954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

please help with insertion sort

I am trying to do an insertion sort that reads from a file it has it own class but i can not get the program to do anything it says no errors but crashes when i try to run

#include <string>

using namespace std;

class Student { 
 public: 
   string lastname; 
   string firstname; 
   string credittakings; 
   string creditearned; 
   string gradepoint; 
   Student * next;


private:      
   Student(string lname,string fname,string credittakings,string creditearned,string gradepoint);
    void set_next(Student *);
   Student* get_next();
   //bool operator > (Student& op1);

   void print_output();
}; 

void Student::print_output()
{
    cout <<" ******************************** " << endl;
    cout << "LastNAME " << "     " << lastname << endl;
    cout << "FirstName" << "     " << firstname << endl;
    cout << "CreditTakings" << "      " << credittakings << endl;
    cout << "CreditEarned " << " " << creditearned << endl;
    cout << "GradePoint " << " " << gradepoint << endl;
}



#include <iostream>
#include "string"
#include "student.h"
#include <fstream>
using namespace std;



Student* list[20]; 

int main() 
{
   string lastname; 
   string firstname; 
   string credittakings; 
   string creditearned; 
   string gradepoint;  
    
    
   //fstream inFile("students.txt"); 
   ifstream inFile("students.txt");
   //3 ofstream outFile;  //output file stream variable
     //outFile.open("output10p1.txt"); //open outfile
   
   //check if file opened
   if (!inFile)
	{
		cout<< "Can not open file student.txt"<<endl;
		return 0;
	}
     //declare variables 
     char str[128]; 
     int i=0, c;            
    
    while (!inFile.eof()) 
    { 
       inFile.getline(str, 128); 
        string line = str; 
        int pos1 = line.find(",");
        string lastname = line.substr(0,pos1);
        int pos2 = line.find(",",pos1+1); 
        string firstname = line.substr(pos1+1,pos2-pos1-1); 
        int pos3 = line.find(",",pos2+1);
        string credittakings = line.substr(pos2+1,pos3-pos2-1);
        string creditearned = line.substr(pos3+1,line.length()-pos3-1); 
        //int pos4=line.find(",",pos3+1);
		//string gradepoint = line.substr(pos4+1,line.length()-pos4-1);
        //string gradepoint = atof(grade.c_str()); 
        

		
        //list[i] = new Student; 
        list[i] ->lastname = lastname; 
        list[i] ->firstname = firstname; 
        list[i] ->credittakings = credittakings; 
        list[i] ->creditearned = creditearned;
		list[i] ->gradepoint= gradepoint;
        i++;
    
    }
    // SAVE THE CURRENT VALUE OF THE LOOP COUNTER. IT'S THE STUDENTS COUNT
    int count = i;
                           
    // loop will keep function until user enters "0"
    while (true)
    {
        //(0 to quit)
        cout<<"Which column would you like to sort by (0 to quit) ==> "<<endl; 
          cout<<"1) Last Name"<<endl<<"2) first Name"<<endl;
    
		cin>>c;  
         
        // if "0" is entered loop will terminate
        if (c == 0)
            break;

        // Loop Runs Til Count == Number Of Students Read
        for (i=0; i < count; i++)
        {
            for (int j=i+1; j < count; j++)
            {
                
                switch (c)
                {
                case 1: if (list[i]->lastname > list[j]->lastname){
                    Student* tmp = list[i];
                    list[i] = list[j];
                    list[j] = tmp; 
                    break;
                        }
                case 2: if (list[i]->firstname > list[j]->firstname){
                    Student* tmp = list[i];
                    list[i] = list[j];
                    list[j] = tmp; 
                    break;
                        }
                
                    
                }
                
            }
            
        }
          cout <<"+-----------+-------------+---------------------+------------------------------------------------+"<<endl;
        cout <<"|Last Name |  First Name  |      CreditTakings         |      CreditEarned        |    GradePoint|"<<endl;
          cout <<"+-----------+-------------+---------------------+------------------------------------------------+"<<endl;
          
          // statement to output sorted table
        for (i=0; i< count; i++)
        {
               cout <<list[i]->lastname<<"\t    |   "<<list[i]->firstname<<"\t  |  "<<list[i]->credittakings<<"\t| ";
			   cout <<list[i]->creditearned<<"\t     |"<< list[i]->gradepoint<<"\t     |"<< endl;
        }
          cout <<"+-----------+-------------+---------------------+--------------------+"<<endl;
      

     }
    return 0; 
}

the text file is

Johnson Christy 12 85 2.5
Lewis Breana 15	45 3.2
Adams Brittany 13 25 4.0
Mcallister Terrance 16 90 3.7
Johnson Darius 14 25 2.0


<< moderator edit: added code tags : [code][/code] >>

christyj5
Newbie Poster
7 posts since Sep 2004
Reputation Points: 10
Solved Threads: 0
 

Maybe you shoud read sorting tutorial from
www.eternallyconfuzzled.com

Micko
Junior Poster
148 posts since Aug 2005
Reputation Points: 55
Solved Threads: 6
 

I view programming as a four step process. First I have to have the inspirition to start a project (or it is something I'm forced to do). Second, I have to think my through the project, usually ruining several pages of paper filled with failed algorithms. Third I write the program. And fourth I debug the program. Except, that I try to do step three and four at the same time. How? By writing a single function at a time, and more often only a few lines at a time, and debugging them before moving on. Even then, I often get an entire program to compile but it hangs, or it fails to develop the correct answer to known scenarios, or fails in some other fashion because I don't find all the bugs in my code, or flaws in my logic for that matter, by the time I'm done writing the code. That's when the hard stuff starts--run time debugging. I usually start by commenting out funtctions until I get back to a state that does do what I want and focus on the implicated function. Now, I don't do this for a living, and I don't have class projects I have to complete on time, so I can usually putz my way through things, but I suspect that many successful programmers use a similar process to complete their projects. SO, what I'd recommend is go back to the beginning and start from scratch again OR start from the end and work your way back. Either way, you'll benefit by using a debugger to follow variables through from one step to the next, or start adding a bunch of output statement to make sure the values are as expected each step along the way. When you've narrowed down the problem it's easier to find a solution on your own, or to ask a focused question so others can help you in an efficient and satisfying manner.

Good luck.

Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

This is an array of 20 pointers to Student .

Student* list[20];


Where do you allocate memory for each of these 20 pointers?

Or did you instead mean to make an array of 20 Student s? That would be like this.

Student list[20];


But your use of -> notation would then need to be changed to . instead. There would need to be other changes as well to get it to compile.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

I tried to start over and read the example in the book but I am getting errors with this program .


#include
#include
#include
#include
using namespace std;

struct student
{
string creditearned;
string a [100];
string credittaking;
string gradepoint;
string lastname;
string firstname;
};

void insert(student x[], const int n)
{
// insert element n in proper location
// in an array whose elements 0..n-1
// are already in ascending order
student t=x[n]; // element to be inserted
// move elements larger than t forward
int i;
for (i = n-1; i >= 0 && x[i] > t; i--)
x[i+1] = x[i];
// put t in last vacated location
x[i+1] = t;
}

void inssort(student x[], const int size)
{
// sort array of size elements into ascending order
// Starting with sorted part length 1, insert each
// successive element into proper location
for (int i=1; i> lastname)
{
if (count >= MAX) throw 1;
a[count].lastname = lastname;
inp >> a[count].firstname;
inp >> a[count].creditearned;
inp >> a[count].credittaking;
inp >> a[count++].gradepoint;
}
return count;
}

//double t;
//int i(0);
//while (cin >> t)
//{
//if (i >= max) throw 1;
//x[i++] = t;
//}
//return i;
//}

void printarr(student a[], const int size)
// print an array of doubles in fixed format, D decimal positions,
// E elements, each C columns wide, to a line
{
for (int i = 0; i

christyj5
Newbie Poster
7 posts since Sep 2004
Reputation Points: 10
Solved Threads: 0
 

When I think of an insertion sort I think of starting with a collection of unsorted items (say array a) and I sort them as I insert them into a second collection (say array b). That means I need some attribute to do the sorting--in this case the last name seems to be a reasonable. Thus if the first student in a was Jones I'd put that in the first element of the array b. If the second student was Smith I'd put it in the second element of the array b. If the third student was Miller I'd put it between Jones and Smith in b. By the time I got done with array a, array b will be sorted by last name and I could read array b back into array a. Alternatively, I could just insert appropriately into array a as I was reading in from the file, and save myself a number of steps, but that may not be possible in your case.

To accomplish that task with code I'd look at each student's last name in the array busing a loop. As soon as I found a name (at position n) that comes after the one I'm trying to put into the array b alphabetically, I want to move all names from position n to the end of the array b to the right by one starting with the last name already in array b, and then insert the current student from array a into array b at position n. Thus, to do an insertion sort I would need the array (or another container) to insert into, the student to insert, the position of the desired insertion in array b and the number of students in array b already.

Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

I'm posting this very small insertion sort routine in C - well after your post, and possibly a homework deadline, so you can see what one looks like.

typedef THING unsigned long;
/* n= number of elements in *input */
void insertion(THING *input, int n)
{ 
    int i=0, j=0;
    THING tmp=0;
    for (i = 1; i < n; i++)
    { 
        tmp = input[i];
        j = i;
        while ((j > 0) && (input[j-1] > tmp))         
        { 
            input[j] = input[j-1];
         	j--;         
        } 
        input[j] = tmp;     
      } 
}

It's really like a deferred "swap" function - you swap only after
you find where the element belongs.

jim mcnamara
Junior Poster
180 posts since May 2004
Reputation Points: 62
Solved Threads: 10
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You