GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 07-Dec-2008, 23:23
Frenchy Frenchy is offline
New Member
 
Join Date: Dec 2008
Posts: 3
Frenchy is on a distinguished road

Sorting with struct and arrays


Hey guys, i really need help with this problem, it s due by Tuesday and i hope someone will be able to help me with this.

This program works perfectly fine, i just need to add a sorting function that would sort either the exams, grade, avg, or even the name using the struct.
I am reading from a file called "studInfo.txt" and displaying the results on "output.txt". I would need to sort any of the following and display the result in the program itself, not the "output.txt".

So if someone could help me, i would greatly appreciate. I would rather have someone helping me sorting the exams or avg from the struct.
Thank you very much

Here is the studInfo needed:

Code:
stud1 90 90 90 stud2 80 80 80 stud3 80 80 80 stud4 70 70 70 stud5 85 85 85

Here is the code, which works perfectly fine...just needs a sorting function:

CPP / C++ / C Code:
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
#include<cstdlib>
using namespace std;

#define outFile "output.txt"
#define inFile "studInfo.txt"

struct Grades
{
	float exams[3];
	float avg;
	string lname;
	char grade;
};

char lGrade(float avg);
void write(ofstream& out, Grades);
int read(ifstream & in, Grades studs[]);
int search(const Grades studs[], int numberUsed, string target);

int main()
{
	//Variable declaration
	Grades studs[30];//Array of structures
	float avg, total = 0.0;
	int numStuds, index;
	string target;
	ofstream out;
	ifstream in;
	
	out.open(outFile);
	if (out.fail())
	{
		cerr<<"***ERROR: Cannot open " <<outFile
			<<" for output." << endl;
		out.close();
		return EXIT_FAILURE; 
   }

   in.open(inFile);
   if (in.fail())
   {
	   cerr<<"***ERROR: Cannot open " <<inFile
		   <<" for input." << endl;
	   in.close();
	   return EXIT_FAILURE; 
   }

   //Variable initialization
   int ch;

   //Dynamic entry of the data
   numStuds = read(in, studs);
   for(int i = 0; i < numStuds; i++)
   {
	   total = 0;
		for (int j = 0; j < 3; j++)
			{
				//calculation
				total += studs[i].exams[j];
			}
		studs[i].avg=total / 3.0;
		avg = studs[i].avg;
		//letter grade: call the lGrade function
		
		studs[i].grade = lGrade(avg);
		//display the results
		write(out,studs[i]);	
   }
	out.close();
	in.close();

	//Search section
	cout<<"Please enter the student's last name: ";
	cin>>target;

	//Call the function
	index = search(studs, numStuds, target);
	if (index != -1)
		cout<<"The letter grade for "<<target<<" is "<<studs[index].grade<<endl;
	else
		cout<<"The student is not enrolled in the course."<<endl;

	return 0;
}
int read(ifstream &in, Grades studs[])
{
	int ch; int i = 0;

	while(ch = in.peek() != EOF)
	{
		in >> studs[i].lname;
	
		for(int a = 0; a < 3; a++)
			in >> studs[i].exams[a];
		i++;
	}
	return(i);
}
char lGrade(float avg)
{
	//Declare variable
	char grade;

	//Calculate letter grade
	if(avg >= 90)
		grade = 'A';
	else if (avg >= 80)
		grade = 'B';
	else if (avg >= 70)
		grade ='C';
	else if (avg >= 60)
		grade = 'D';
	else
		grade = 'F';
	return grade;
}

void write (ofstream& out, Grades studs)
{
	out<<setiosflags(ios::fixed)<<setprecision(2);
	out<<"Name: "<<studs.lname<<endl
		<<"Average: "<<studs.avg<<endl
		<<"Grade: "<<studs.grade<<endl<<endl;	
}
int search(const Grades studs[], int numberUsed, string target)
{
	int index = 0;
	bool found = false;
	while ((!found) && (index < numberUsed))
		if (target == studs[index].lname)
			found = true;
		else
			index++;

		if (found)
			return index;
		else 
			return -1;
}
Last edited by admin : 08-Dec-2008 at 00:39. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #2  
Old 08-Dec-2008, 11:13
L7Sqr L7Sqr is offline
Member
 
Join Date: Jul 2005
Location: constant limbo
Posts: 234
L7Sqr is a jewel in the roughL7Sqr is a jewel in the rough

Re: Sorting with struct and arrays


Wouldnt by chance be in the same class as this guy, would you?
__________________
My personal site: Utilities for text processing, debugging, testing and plotting
  #3  
Old 08-Dec-2008, 11:37
Frenchy Frenchy is offline
New Member
 
Join Date: Dec 2008
Posts: 3
Frenchy is on a distinguished road

Re: Sorting with struct and arrays


haha yea, we are actually pretty much partners...but i wanted to try and see if someone else would give better explainations to this problem. Previous answers to this problem did not help very much.
Do you have any idea how to do this...sort in a fucntion using the struct?
  #4  
Old 08-Dec-2008, 16:26
nostaque nostaque is offline
New Member
 
Join Date: Oct 2008
Posts: 19
nostaque will become famous soon enough

Re: Sorting with struct and arrays


PHP Code:

just needs a sorting function 



Adding a line below to your struct and write your regular sorting algorithm.

bool operator < (const Grades& rhs) {return avg < rhs.avg;}

you can replace avg by other variable in your struct for comparision.
  #5  
Old 08-Dec-2008, 18:23
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Sorting with struct and arrays


Quote:
Originally Posted by Frenchy
...Do you have any idea how to do this...sort in a function using the struct?

Suppose you have an array of n "somethings."

If you want to sort the array, you must have defined some ways of determining whether one "something" is less than another "something," whether one "something" is equal to another "something," and whether one "something" is greater than another "something." (Otherwise, how can you tell whether it is sorted? Not only wouldn't you not know where to start; you wouldn't know when you were done!)

The principle of the bubble sort can be illustrated as follows (where I use C language notation for the loops):

Code:
for (i = 0; i < n; i++) { for {j = 0; j < n-1; j++) { if (element[j] "is greater than" element[j+1]) { swap the values of element[j] and element[j+1] } } }


After the code has executed both of the loops all of the times, the smallest element will be first and the largest will be last in the array. There are more efficient ways (and there are simple improvements of the bubble sort to make it more efficient), but at first, let's stick with something that works and is relatively easy to understand.

What the heck do I mean by an array of "somethings"?

You could have an array of integers. You could have an array of floats. You could have an array of structs. The sorting procedure and principle is the same for all.

If the arrays are numerical data types (integers or floats or doubles) there are built-in comparison operators '<', '==' and '>' for "is less than," "is equal to," and "is greater than."

Here is a complete example for arrays integers:

CPP / C++ / C Code:
#include <iostream>

using namespace std;

void isort(int x[], int n);

int main()
{
    int size = 5;
    int iarray[5] = {5,4,3,2,1};

    int i;

    cout << "Initially:   ";
    for (i = 0; i < size; i++) {
        cout << "  " << iarray[i];
    }
    cout << endl;

    isort(iarray, 5);

    cout << "After isort: ";
    for (i = 0; i < size; i++) {
        cout << "  " << iarray[i];
    }
    cout << endl;
    return 0;
}


void isort(int x[], int n)
{
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n-1; j++) {
            if (x[j] > x[j+1]) {
                int temp = x[j];
                x[j] = x[j+1];
                x[j+1] = temp;
            }
        }
    }
}

Output:
Code:
Initially: 5 4 3 2 1 After isort: 1 2 3 4 5

Now if you have an array of structs of your own design, there is, obviously, no built-in operator to compare relative values of the structs.

Consider your struct:

CPP / C++ / C Code:
struct Grades
{
	float exams[3];
	float avg;
	string lname;
	char grade;
};
.
.
.
Grades studs[30]; //An array of 30 structs
.
.
.

If you want to sort according to the struct data member string "lname", you can use the standard string comparison operator ">" in the sort loops:
CPP / C++ / C Code:
for (i = 0; i < n; i++) {
    for {j = 0; j < n-1; j++) {
        if ( studs[j].lname > studs[j+1].lname) {
           // Here is a way to swap the values of studs[j] and studs[j+1]
           Grades temp = studs[j];
           studs[j] = studs[j+1];
           studs[j+1] = temp;
           }
        }
    }
}

Using this code, you can make a function for sorting Grades structs by lname. Just follow the design of isort() above.
CPP / C++ / C Code:
void lnamesort(Grades stud[], int n)
{
// Put stuff here to sort by comparing lname members of the struct elements.
}

Now, what if you want to sort according to avg? Make a pair of loops wherein the comparison uses the avg members:
CPP / C++ / C Code:
.
.
.
        if (studs[j].avg > studs[j+1].avg) {
        // swap studs[j] and studs[j+1]
        .
        .
        .

Since the code inside the loop is different from the previous example, if you want to make this sort routine a function, it will be a different function from the one above.

As you get more "into" it, you may discover that there are ways of making a single sort function that can work on anything that you want, but you have to, somehow, tell it how to do the comparison.

Bottom line: Regardless of the type of sort procedure, all sort routines need some way of knowing how to do the comparison.

Regards,

Dave
Last edited by davekw7x : 08-Dec-2008 at 18:54.
  #6  
Old 08-Dec-2008, 23:18
Frenchy Frenchy is offline
New Member
 
Join Date: Dec 2008
Posts: 3
Frenchy is on a distinguished road

Re: Sorting with struct and arrays


WOW DAVE, thank you sooo much, this really helped, right on time too!
I greatly appreciate your time.

Thank you so much,

Frenchy
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Sorting (structures and arrays fun fun..) odin607 C Programming Language 7 08-Feb-2008 18:58
2D arrays:dynamic allocation and freeing bravetanveer C Programming Language 48 27-Nov-2007 16:55
Arrays as function arguments - return arrays from functions pisuke C Programming Language 2 25-Jul-2007 12:03
Linked list wedel C Programming Language 9 24-Jun-2007 23:45
working with struct and array sasukekun C++ Forum 2 06-May-2006 00:27

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 07:40.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.