C++ help

egeekial

Member
Jan 1, 2002
164
0
0
Yes, this is for a class. I don't want anyone to write it for me. I just don't understand exactly how to implement a few things...

Ok, I have a file with names and grades in it, one name and 5 grades on each line. I have a function that takes one line and puts it into a structure array StudentInfo stud_info[24]. I have an array since there is more than one student. Well, the problem is that I need a function that takes the current line and puts it alphabetically into the right place in the array StudentInfo stud_info[24].

All I need to do is locate the position where to insert the student and move all the students starting from this position one position down, and insert the data, but I don't know exactly how I should go about doing that without a ridiculous amount of excess code.

Another thing is my ReadLine function. If you look at the attached code, you can see the entire function. Well, initializing with the pointer doesn't exactly work right, and I don't know why.

void ReadLine(istream &inp, StudentInfo *student) { ... }

this is how I'm calling it:
while (! inp.eof() ){
ReadLine(inp, stud_info[count]);
PrintGrades(out, stud_info, count);
count++;
}


I hope I was thorough enough without giving too much information. If you made it this far, thanks for reading!
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
For the first part the general algorithm is:

-use a StudentInfo pointer to trace down the array that you already have
-assuming they're already sorted (that's key) start with the first and do a strcmp. If you need to move farther, increment the pointer and repeat.
-now that you've found the place you need to insert, declare a temporary StudentInfo (unless you want to work from the end back)
-copy the StudentInfo at the current location into the temp and replace it with your new data. Increment the pointer and repeat till you hit the end

Do you know for a fact that you will have at most 24 records? If not a linked list seems like a better idea and it would be a little easier to do the insertions
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
> already sorted is key

He means it's safe to search from the start, find the first name after your new one, and know that everyone after that in the list does need to be pushed forward by one. You only know that is true because you're always adding a new item in sorted order.

When you say "ridiculous amount of excess code" do you mean you're not just going to use a one loop to push things forward to make room for the new item?

Tip: once you've found the right spot, consider a loop with a decrement to do the moving.
 

egeekial

Member
Jan 1, 2002
164
0
0
That goes into an endless loop or something... cpu usage goes up to 100% and program freezes.. what did I do wrong?
 

BFG10K

Lifer
Aug 14, 2000
22,709
3,003
126
Stick some good ol' debug statements to figure out where it gets stuck.