structs

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 956 Views - Last Post: 04 May 2012 - 02:45 PM Rate Topic: -----

#1 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

structs

Posted 28 April 2012 - 09:18 AM

So my problem is to turn a program I made into using a struct to store each student's data and an array of structs to store the whole class. The struct should have a data member for id, score, and grade.
// File: stugrades.cpp
// Computes a external file and compiles it into a table with 3 columns of ID numbers, scores, and corresponding scores.

#include <iostream>  
#include <fstream> // re. ifstream object  
#include <iomanip> // re. setw, setprecision, fixed in formatted output 
 

    
using namespace std;
  
   
int main()
{  
	ifstream fin( "grades.txt" );   // construct ifstream object fin 

	if( fin ) 			// if opened ok ...  

	{  
		cout << "Student ID" << "      " << "Average Score" << "       " << "Corresponding Grade" << endl;  

		int id; 
		string grade; 
		int count = 7;
		float average;
		
		int mean = 72.8;
		
		while( fin >> id )  
		{  
			int sum = 0, score[7];
			//int mean = 0, average[7];  

			for( int i = 0; i < 7; ++ i )  

		{  

			fin >> score[i];  

			sum += score[i]; 

			average = (sum / count); 
		
					if (average > mean + 10)
					{
						grade = "outstanding";
					}
					else if (average < mean - 10)
					{
						grade = "unsatisfactory";
					}
					else if ((average <= mean + 10) && (average >= mean - 10))
					{
						grade = "satisfactory";
					}
				
		} 
			 

		cout << "   " << id << "       " << "       " << average << "         " << "       " << grade << endl;

	}  

	fin.close(); // since done with file now ...  

	} 
}



The grades file is simply...
3313	90	42	58	64	70	75	100
5688	88	48	79	70	79	70	94
4700	50	44	89	73	70	73	100
9561	88	69	88	87	84	63	98
3199	96	69	100	90	88	67	100
3768	78	57	80	59	57	15	60
8291	72	56	70	82	74	9	83
7754	76	62	93	100	78	41	58
8146	94	68	99	94	93	9	54
2106	98	47	96	94	70	27	100





I've only been briefly introduced to structs. I think somthing like this would be the start of my struct....

struct examStats
{
    float id;
    int scores;
    string grade;
    float mean;
    float sum;
}



This Posted Image is an opening code tag. The whole thing. A pair of brackets [ ] with the word code between them. This tag goes before your code.

This Posted Image is a closing code tag. A pair of brackets [ ] with /code inside. This tag goes after your code.

This post has been edited by r.stiltskin: 28 April 2012 - 09:28 AM
Reason for edit:: Added code tags. Please learn to use them.


Is This A Good Question/Topic? 0
  • +

Replies To: structs

#2 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1831
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: structs

Posted 28 April 2012 - 09:33 AM

You need a semicolon after the closing brace of the struct definition: };

And since each student will probably have multiple scores, you might want to make the scores member of the struct an array.

Oh, and why is ID a float? Why not a string? Presumably you won't be doing arithmetic with the IDs.
Was This Post Helpful? 1
  • +
  • -

#3 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,662
  • Joined: 20-September 08

Re: structs

Posted 28 April 2012 - 05:20 PM

Quote

So my problem is to turn a program I made into using a struct to store each student's data and an array of structs to store the whole class. The struct should have a data member for id, score, and grade.


It seems you just want to print out three grades ...

> mean + 10
< mean - 10
all the rest will be in between the above ...

If this is the case, you do not need a 'grade' string member in your struct ...

Just calculate the mean for each student, and print out one of the three output messages

You could make a function to do this if you like, something like this:

string getGradeStr( double classMean, double studentMean )
{
   if( /* ... */ ) return "your message 1 ... ";
   if( /* ... */ ) return "your message 2 ... ";
   // else ...
   return "your message 3 ... ";
}




Also ... as "r.stiltskin" suggested above, using a C++ string to hold your student ID is generally helpful, since then the id can be as long as you wish and not limited to int's with digits 0..9

But note that int's sort differently than strings of digits ...

For example:

After a normal ascending order sort ...

for strings ...

111
22
3


but for int's ...
3
22
111


Also note changes below ...

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
    const int numScores = 7;
    const double classMean = 73.1;
    ifstream fin( "grades.txt" );

    if( fin )
    {
        cout << "Student ID" << "      " << "Average Score" << "       "
             << "Corresponding Grade" << endl;

        string id, grade;

        while( fin >> id )
        {
            int sum = 0, score[numScores];

            for( int i = 0; i < numScores; ++ i )
            {
                fin >> score[i];
                sum += score[i];
            }

            // ONLY AFTER all scores input for this student, can you NOW find...
            double average = double(sum)/numScores; // first get int sum to type double

            if( average > classMean + 10 )
            {
                grade = "outstanding";
            }
            else if( average < classMean - 10 )
            {
                grade = "unsatisfactory";
            }
            else
            {
                grade = "satisfactory";
            }

            // output results as you wish, for example ...
            cout << "For " << id << ", grade was " << grade << endl;

            // ok ... get next line, (if it exists), from file and process ...

        }
        fin.close();
    }
}


This post has been edited by David W: 29 April 2012 - 12:07 AM

Was This Post Helpful? 0
  • +
  • -

#4 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

Re: structs

Posted 29 April 2012 - 06:29 AM

so basically, a struct is just different types of related data that are stored in different parts of the program?

Should the program ask the user to enter a id number and then the user will get the results of that person?
Was This Post Helpful? 0
  • +
  • -

#5 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1831
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: structs

Posted 29 April 2012 - 06:54 AM

View Postcscstudent1991, on 29 April 2012 - 09:29 AM, said:

so basically, a struct is just different types of related data that are stored in different parts of the program?

I'd rephrase that and say that a struct enables you to take different types of data that are logically related in some way
and store them together in a single "container". In this case the data are logically related in that they all apply to a particular student.

Quote

Should the program ask the user to enter a id number and then the user will get the results of that person?

The processing should be similar to what you did in your previous program, prompting for an id number, then prompting for the scores belonging to that id, then calculating and storing the average and the grade for that id.

The biggest difference between this one and your earlier program is that those procedures should be done in a loop that repeats the same process for each of the students, saving each student's information in an array of structs.

Then after that loop, you can write another loop that reads the info from the array of structs one at a time and prints the summary report to the screen.
Was This Post Helpful? 1
  • +
  • -

#6 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

Re: structs

Posted 29 April 2012 - 08:16 AM

Okay so I put what I am thinking is a struct but very poorly written. (I want to apologize I am taking a 6 week crash course in c++ and I have never seen any of this before. I did fine up until arrays and structs)

// File: stugrades.cpp
// Computes a external file and compiles it into a table with 3 columns of ID numbers, scores, and corresponding scores.

#include <iostream>  
#include <fstream> // re. ifstream object  
#include <iomanip> // re. setw, setprecision, fixed in formatted output 
 

    
using namespace std;
  
   
int main()
{  

	ifstream fin( "grades.txt" );   // construct ifstream object fin 

	if( fin ) 			// if opened ok ...  

	{  

		cout << "Student ID" << "      " << "Average Score" << "       " << "Corresponding Grade" << endl;  

		int id; 
		string grade; 
		int count = 7;
		float average;
		
		int mean = 72.8;
		
		while( fin >> id )  
		{  

			int sum = 0, score[7];
			//int mean = 0, average[7];  

			for( int i = 0; i < 7; ++ i )  

		{  

			fin >> score[i];  

			sum += score[i]; 
					

			average = (sum / count); 

			string student.Id;
			int student.Scores[6];
			const int SENTINEL = -1;
			
			void readStudent
				(student& student)

			while( student.id != SENTINEL )
			{
				cout << "Enter data for new student and enter -1 to end" << endl;
				cout << "Enter student ID.";
				cin >> student.Id;
				cout << "Enter scores.";
				cin >> student.Scores;

			}
		
				
				
					
				
					if (average > mean + 10)
					{
						grade = "outstanding";
					}
					else if (average < mean - 10)
					{
						grade = "unsatisfactory";
					}
					else if ((average <= mean + 10) && (average >= mean - 10))
					{
						grade = "satisfactory";
					}
				
		} 
			 

		cout << "   " << id << "       " << "       " << average << "         " << "       " << grade << endl;
        

	}  

	fin.close(); // closes file  

	} 

}


Was This Post Helpful? 0
  • +
  • -

#7 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1831
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: structs

Posted 29 April 2012 - 08:31 AM

Your original struct examstats that you posted in Post #1 was good, except that I would make id a string, and it needed an array of scores instead of just 1 score, for example, if there will be 7 scores per student:
int scores[7];


The struct definition goes near the beginning of your program, before the main function. Now your examstats is a new data type.

Inside the main function, declare an array of examstats, the same way you would declare an array of int. If there are 20 students, that would be

examstats student_data[20];


Now student_data[0] is an examstats struct.
And student_data[1] is an examstats struct.
And so on.

And student_data[0].id is the first student's id.
student_data[0].scores is the first student's array of scores.
student_data[0].scores[0] will hold the first student's first score.
student_data[0].scores[1] will hold the first student's second score.

student_data[10].scores[1] will hold the 11th student's second score.

Does that help clear things up a bit?
Was This Post Helpful? 1
  • +
  • -

#8 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

Re: structs

Posted 29 April 2012 - 09:40 AM

Yes it does, However, I feel like I am missing certain variables. So your saying that the struct code needs to be placed outside of int main?

like...

// File: stugrades.cpp
// Computes a external file and compiles it into a table with 3 columns of ID numbers, scores, and corresponding scores.

#include <iostream>  
#include <fstream> // re. ifstream object  
#include <iomanip> // re. setw, setprecision, fixed in formatted output 
 

    
using namespace std;

			void readStudent
				(examStats student)
			{
				cout << "Enter data for new student and enter -1 to end" << endl;
				cout << "Enter student ID.";
				cin >> student_id;
				cout << "Enter scores.";
				cin >> student_data;

			}

			
   
int main()
{  

	ifstream fin( "grades.txt" );   // construct ifstream object fin 

	if( fin ) 			// if opened ok ...  

	{  

		cout << "Student ID" << "      " << "Average Score" << "       " << "Corresponding Grade" << endl;  

		string id; 
		string grade; 
		int count = 7;
		float average;
		examStats student_id[20];
		examStats student_data[20];
		const int SENTINEL = -1;
		int mean = 72.8;
		
		while( fin >> id )  
		{  

			int sum = 0, score[7];
			//int mean = 0, average[7];  

			for( int i = 0; i < 7; ++ i )  

		{  

			fin >> score[i];  

			sum += score[i]; 
					

			average = (sum / count); 

			
			
			
			//while( student.id != SENTINEL )
			
  
			
			
		
				
				
					
				
					if (average > mean + 10)
					{
						grade = "outstanding";
					}
					else if (average < mean - 10)
					{
						grade = "unsatisfactory";
					}
					else if ((average <= mean + 10) && (average >= mean - 10))
					{
						grade = "satisfactory";
					}
				
		} 
			 

		cout << "   " << id << "       " << "       " << average << "         " << "       " << grade << endl;
        

	}  

	fin.close(); // closes file  

	} 

}



Was This Post Helpful? 0
  • +
  • -

#9 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1831
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: structs

Posted 29 April 2012 - 09:45 AM

No, not the "struct code", just the struct definition.

All "running code" must always be inside some function.

This is a struct definition
struct examStats
{
    float id;
    int scores;
    string grade;
    float mean;
    float sum;
};

but it needs some minor changes as discussed above.
Was This Post Helpful? 1
  • +
  • -

#10 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,662
  • Joined: 20-September 08

Re: structs

Posted 29 April 2012 - 01:14 PM

If you look more closely at this example ...

http://www.dreaminco...ost__p__1609834

you may 'see' how one can easily input data into an array of struct ... from a file that is known to have well structured data ...

P.S.

Do you know how to code and use functions ... to break up your program into smaller steps ... and to aid in program developement and logic flow?

If not, you could look at this often recommended DIC tutorial for starters ...

http://www.dreaminco...t-i-the-basics/

And/Or look at "Six Fast Steps to Programming in C++" ... (if you are logged in) ... see my "Beginning Computer Programming with C++..." link below


Coding can be a very consise language ... i.e. many specifics get implied by 'saying' just a very few 'code' words.

You may also like to see this 'input-loop' with the newly added comments:

// this function uses the global file name FNAME ...
// address of empty StudentGrades ary is passed in, so filled array is accessible from 'calling scope'
// local copy of max_num passed in to allow code to prevent array 'overflow'
// if FNAME file is NOT opened ok ... array not filled, -1 error value/flag returned
// if file opened ok ... function returns the number of file 'records' read from file, up to
// the max_num tested for ...in the 1st place of the while loop test
int fillFromFile( StudentGrades ary[], int max_num )
{
    ifstream fin( FNAME ); // construct ifstream object fin ...
    if( fin ) // if opened ok ...
    {
        int i = 0;
        // Note: this 'while' loop will stop when MAX_SIZE reached or no more lines
        while( i < max_num && fin >> ary[i].id )
        {
            for( int j = 0; j < NUM_TESTS; ++ j )
                fin >> ary[i].scores[j]; // for this 'i'th struct in the array of struct's ...
					 // fill 'this scores array' at index j  = 0 to NUM_TESTS-1

            ++i; // ok ... increment i to get ready for next 'struct' in array ...
        }
        fin.close();
 
        return i; // return number of 'records' read from file ...
    }
    else return -1; // value of 'file open error flag' ...
}

This post has been edited by David W: 29 April 2012 - 10:23 PM

Was This Post Helpful? 0
  • +
  • -

#11 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

Re: structs

Posted 01 May 2012 - 06:53 AM

ah okay THANK YOU
Was This Post Helpful? 0
  • +
  • -

#12 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

Re: structs

Posted 02 May 2012 - 10:29 AM

so heres my code. Does anyone know how to put them in order from greatest grades to lowest? I have to make a "bubble sort" but the book doesn't say anything about bubble sorting because its a "critical thinking" question.

// File: stugrades.cpp
// Computes a external file and compiles it into a table with 3 columns of ID numbers, scores, and corresponding scores.

#include <iostream>  
#include <fstream> // re. ifstream object  
#include <iomanip> // re. setw, setprecision, fixed in formatted output 
 

    
using namespace std;

			

			struct examStats  

			{  
				string id;  
				int scores;  
				string grade;  
				float average;  
				float sum;  
			}; 


			
   
int main()
{  

	ifstream fin( "grades.txt" );   // construct ifstream object fin 

	if( fin ) 			// if opened ok ...  

	{  

		 

		string id; 
		string grade; 
		int count = 7;
		float average;
		string student;
		int mean = 72.8;
		examStats student_data[10];
		
		while( fin >> id )	//removed a >  
		{  

			
			int sum = 0, score[7];
			//int mean = 0, average[7];  

			for( int i = 0; i < 7; ++ i )  

		{  

			fin >> score[i];	// removed a >  

			sum += score[i]; 
					

			average = (sum / count); 

			
			student_data[0].id = id;
			student_data[0].scores = score[0];
			student_data[1].scores = score[1];
			student_data[2].scores = score[2];
			student_data[3].scores = score[3];
			student_data[4].scores = score[4];
			student_data[5].scores = score[5];
			student_data[6].scores = score[6];
			student_data[0].grade = grade;
			student_data[0].average = average;
			student_data[0].sum = sum;


  
			
			
		
				
				
					
				
					if (average > mean + 10)
					{
						grade = "outstanding";
					}
					else if (average < mean - 10)
					{
						grade = "unsatisfactory";
					}
					else if ((average <= mean + 10) && (average >= mean - 10))
					{
						grade = "satisfactory";
					}
				
		} 
			 

		cout << student_data[0].id << endl;
		cout << student_data[0].scores << " " << student_data[1].scores << " " << student_data[2].scores << " " << student_data[3].scores << " " << student_data[4].scores << " " << student_data[5].scores<< " " << student_data[6].scores << endl; 
		cout << student_data[0].average << endl;
		cout << student_data[0].grade << endl;
		cout << student_data[0].sum << endl;
        	cout << endl;

	}  

	fin.close(); // closes file  

	} 

}



Was This Post Helpful? 0
  • +
  • -

#13 simeesta  Icon User is offline

  • Deadly Ninja


Reputation: 195
  • View blog
  • Posts: 544
  • Joined: 04-August 09

Re: structs

Posted 02 May 2012 - 10:37 AM

Bubble sort. The link contains pseudo-code. You just have to decide how to compare your structs. There's plenty of information if you just google it.
Was This Post Helpful? 0
  • +
  • -

#14 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,662
  • Joined: 20-September 08

Re: structs

Posted 02 May 2012 - 11:16 PM

You haven't yet created a proper array of struct ... so that you can sort that array.
So ... that would be a first step.

But ... a more OOP way to do the above ...
#include <iostream>  
#include <fstream> 
#include <iomanip>
#include <string>
 
using namespace std;

// this is all the 'independant' info
// you need to store to define this 'object'

const NUM_SCORES = 7;
struct ExamStats  // with member functions...
{  
   string id;
   int scores[NUM_SCORES]; 

   // return double average of int ary with NUM_SCORES elements ...
   double get_average()
   {
      double sum = 0;
      for( int i = 0; i < NUM_SCORES; ++ i ) sum += scores[i];
      return sum / NUM_SCORES;
   }
   // return grade string
   string get_grade( double class_average )
   {
      if( get_average() > class_average + 10 ) return "outstanding";
      if( get_average() < class_average - 10 ) return "unsatisfactory";
      // else ...
      return "satisfactory";
   }
}; 


int main()
{  
   ifstream fin( "grades.txt" );
   if( fin ) 	// if opened ok ...  
   {
      ExamStats ary[10]; // get memory to hold up to 10 ExamStats objects
      int i = 0; // Note: i is also a counter of number of student records

      // now ... just fill array from file ... 
      while( i < 10 && fin >> ary[i].id )
      {
         for( int j = 0; j < NUM_SCORES; ++ j )
            fin >> ary[i].scores[j];
         ++ i;
      }
      fin.close();

      // now... find class average ...
      double classAverage = 0;
      for( int j = 0; j < i; ++ j ) classAverage += ary[j].get_average();
      classAverage /= i; // classAverage = classAverage / i;

      // now ... output results for i student records ...
      cout << setprecision(2) << fixed;// show 2 decimal places
      for( int j = 0; j < i; ++ j )
      {
         cout << ary[j].id << "   " << ary[j].get_average() << "   " << ary[j].get_grade( classAverage ) << endl;
      }
   }
}


This post has been edited by David W: 03 May 2012 - 11:08 AM

Was This Post Helpful? 0
  • +
  • -

#15 cscstudent1991  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 26-April 12

Re: structs

Posted 03 May 2012 - 08:38 AM

What if I use a standard bubble sort notation? I know I am missing a function prototype and proper calls to that function. I'm not 100% sure how to do that.

// File: sortgrades.cpp
// Computes a external file and compiles it into a table with 3 columns of ID numbers, scores, and corresponding scores.

#include <iostream>  
#include <fstream> // re. ifstream object  
#include <iomanip> // re. setw, setprecision, fixed in formatted output 
 

    
using namespace std;

			

			struct examStats  

			{  
				string id;  
				int scores;  
				string grade;  
				float average;  
				float sum;  
			}; 


			
   
int main()
{  

	ifstream fin( "grades.txt" );   // construct ifstream object fin 

	if( fin ) 			// if opened ok ...  

	{  

		 

		string id; 
		string grade; 
		int count = 7;
		float average;
		string student;
		int mean = 72.8;
		examStats student_data[10];
		
		while( fin >> id )	//removed a >  
		{  

			
			int sum = 0, score[7];
			//int mean = 0, average[7];  

			for( int i = 0; i < 7; ++ i )  

		{  

			fin >> score[i];	// removed a >  

			sum += score[i]; 
					

			average = (sum / count); 

			
			student_data[0].id = id;
			student_data[0].scores = score[0];
			student_data[1].scores = score[1];
			student_data[2].scores = score[2];
			student_data[3].scores = score[3];
			student_data[4].scores = score[4];
			student_data[5].scores = score[5];
			student_data[6].scores = score[6];
			student_data[0].grade = grade;
			student_data[0].average = average;
			student_data[0].sum = sum;


  
			void BubbleSort(average <int> &num)
			{
     				int i, j, flag = 1;   
      				int temp;             
      				int student_data[0].average = average; 
      				for(i = 1; (i <= average) && flag; i++)
     				{
          				flag = 0;
          				for (j=0; j < average -1); j++)
         				{
               					if (average[j+1] > average[j])      
              					{ 
                    					temp = average[j];             
                    					average[j] = average[j+1];
                    					average[j+1] = temp;
                    					flag = 1;              
               					}
          				}
     				
				}

     				return;   
			}

			
		
				
				
					
				
					if (average > mean + 10)
					{
						grade = "outstanding";
					}
					else if (average < mean - 10)
					{
						grade = "unsatisfactory";
					}
					else if ((average <= mean + 10) && (average >= mean - 10))
					{
						grade = "satisfactory";
					}
				
		} 
			 

		cout << student_data[0].id << endl;
		cout << student_data[0].scores << " " << student_data[1].scores << " " << student_data[2].scores << " " << student_data[3].scores << " " << student_data[4].scores << " " << student_data[5].scores<< " " << student_data[6].scores << endl; 
		cout << student_data[0].average << endl;
		cout << student_data[0].grade << endl;
		cout << student_data[0].sum << endl;
        	cout << endl;

	}  

	fin.close(); // closes file  

	} 

}



Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2