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: [co[u][/u]de][/co[u][/u]de] >>

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.

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.

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

#include <iostream.h>
#include <iomanip.h>
#include <string>
#include <fstream>
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 > t; i--)
x[i+1] = x;
// 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<size; i++) insert(x, i);
}


//int readArray(double x[], const int max)
//{
// read up to MAX elements into array, throwing exception
// if limit exceeded. Return number of elements read.


int loadarr(student a[], int MAX)
{
// load phone directory from the file
// /home/sjmccasl/pub/cmsc204/phonenum.dat
// does no error checking. The file is assumed to
// exist and have the proper layout.
#ifdef _M_IX86
// Borland and Visual read file from current folder
ifstream inp("students.txt");
#endif
int count(0); string lastname;
while (inp >> 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<size; i++)


cout<< setw(20)<< a.lastname+ " " + a.firstname<< "\t" << a.creditearned <<"\t" << a.credittaking<< "\t" << a.gradepoint<< endl;
}
int main()
{



int size;
student a[100];
size = loadarr(a, 100);
cout << endl;
printarr(a, size);
inssort(a, size);
cout << "sorted" << endl;
printarr(a, size);
return 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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.