473,387 Members | 1,535 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

question on c++ program using structs/classes

I have written a c++ program that takes input from a file and outputs the average. The program uses structs and I need to convert the struct to a class.

I just dont know how to get started and if I will have to re-write my whole program.

Expand|Select|Wrap|Line Numbers
  1. #include <cstdlib>
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5. #include <fstream>
  6. using namespace std;
  7.  
  8. ifstream in_file;
  9. //structure that holds student record information.
  10. typedef struct records{
  11.         string name;
  12.         float quizes[7];
  13.         float projects[6];
  14.         float exams[2];
  15.         float labs[14];
  16. };
  17.  
  18. const int num_quizes = 7;
  19. const int num_exams = 2;
  20. const int num_projects = 6;
  21. const int num_labs = 14;
  22.  
  23. const int quizes_pts = 70;
  24. const int exams_pts = 200;
  25. const int projects_pts = 300;
  26. const int labs_pts = 150;
  27.  
  28. void get_scores(ifstream& infile, int num_scores, float scores[]);
  29. double get_average(float scores[], int num_scores, int tot_pts, float& average);
  30. void total_average(float average,float& student_average);
  31. void grades_display(int counter,float ave1,float ave2,float ave3,float ave4,float total,char grade);
  32.  
  33.  
  34.  
  35. int main()
  36. {
  37.  
  38.  
  39.             cout << "No.   Name      Quiz   Project   Exam   Lab   Total   Grade"
  40.          << endl;
  41.     cout << "        --- ---------   ----- ---------- ------ ----- -------  -----"
  42.          << endl;
  43.     cout << endl;
  44.  
  45.  
  46.         records grades;
  47.         ifstream in_file;
  48.         // Define a file input stream and open the file
  49.         in_file.open("record.txt"); //opening file
  50.  
  51.         if (in_file.fail())
  52.         {
  53.         // Failed to open the file (file doesn't exist or isn't readable)
  54.         cout << "Could not open file: "<< "\n";
  55.         exit(1);
  56.         }
  57.         float average = 0;
  58.         int counter = 1;
  59.         while(!in_file.eof())
  60.         {
  61.         //get string from the file
  62.         in_file >> grades.name;
  63.  
  64.  
  65.  
  66.         char letter_grade;
  67.         float student_average = 0;
  68.  
  69.  
  70.         // Repeatedly get characters from the file
  71.  
  72.         get_scores(in_file, num_quizes, grades.quizes);   //function for inputing info in struct.
  73.         get_average(grades.quizes, num_quizes, quizes_pts, average); //function for average
  74.         total_average(average,student_average);
  75.         float quiz_average = average;
  76.  
  77.         get_scores(in_file, num_projects, grades.projects); //input project scores
  78.         get_average(grades.projects, num_projects, projects_pts, average);
  79.         total_average(average,student_average);
  80.         float project_average = average;
  81.  
  82.         get_scores(in_file, num_exams, grades.exams); //input exam scores
  83.         get_average(grades.exams, num_exams, exams_pts, average);
  84.         total_average(average,student_average);
  85.         float exams_average = average;
  86.  
  87.         get_scores(in_file, num_labs, grades.labs); //input lab scores
  88.         get_average(grades.labs, num_labs, labs_pts, average);
  89.         total_average(average,student_average);
  90.         float labs_average = average;
  91.  
  92.         student_average = student_average/4;
  93.         grades_display(counter,quiz_average,project_average,exams_average,labs_average,student_average,letter_grade);
  94.  
  95.         counter++;
  96. }
  97.  
  98.  
  99.         // Close the file
  100.     in_file.close();
  101.  
  102.  
  103.     return 0;
  104. }
  105.  
  106.  
  107.  
  108. //function that takes in parameters to input scores in array
  109. void get_scores(ifstream& in_file, int num_scores, float scores[])
  110. {
  111.  
  112.         for (int i = 0; i < num_scores; i++)
  113.         {
  114.          in_file >> scores[i];
  115.  
  116.         }
  117.  
  118. }
  119.  
  120. //funtion that takes the average of the inputed scores
  121. double get_average(float scores[], int num_scores,int tot_pts,float& average)
  122. {
  123.      float a = 0;
  124.  
  125.      for (int i = 0; i < num_scores; i++)
  126.      {
  127.         a = scores[i] + a;
  128.      }
  129.         average = (a/tot_pts);
  130.         average = average * 100;
  131.  
  132.         return average;
  133. }
  134.  
  135. //function to take total average for each member
  136. void total_average(float average,float& student_average)
  137. {
  138.  
  139.         student_average  = average + student_average;
  140.  
  141. }
  142.  
  143. //function to output letter grade and output scores
  144. void grades_display(int counter,float ave1,float ave2,float ave3,float ave4,float total,char grade)
  145. {
  146.  
  147.         if(90 < total)
  148.            grade = 'A';
  149.         if((80 < total)&&(total < 90))
  150.            grade = 'B';
  151.         if((70 < total)&&(total < 80))
  152.            grade = 'C';
  153.         if((60 < total)&&(total < 70))
  154.            grade = 'D';
  155.         if (total < 60)
  156.            grade = 'F';
  157.  
  158.         cout << "         " << counter << "        "  << ave1  << "     " << ave2  << "     " << ave3  << "     " << ave4 << "     " << total << "    " << grade;
  159.  
  160.  
  161.  
  162. }
  163.  

would it be easier to put the class program in separate files
May 12 '07 #1
9 3382
weaknessforcats
9,208 Expert Mod 8TB
Just start with your struct:

Expand|Select|Wrap|Line Numbers
  1. struct records{
  2.         string name;
  3.         float quizes[7];
  4.         float projects[6];
  5.         float exams[2];
  6.         float labs[14];
  7. };
  8.  
;

and put your member function names inside the struct:

Expand|Select|Wrap|Line Numbers
  1. struct records{
  2.         string name;
  3.         float quizes[7];
  4.         float projects[6];
  5.         float exams[2];
  6.         float labs[14];
  7.  
  8.          void get_scores(ifstream& in_file, int num_scores, float scores[]);
  9.  
  10. };
  11.  
Then code the function as:
Expand|Select|Wrap|Line Numbers
  1. //function that takes in parameters to input scores in array
  2. void records::get_scores(ifstream& in_file, int num_scores, float scores[])
  3. {
  4.  
  5.         for (int i = 0; i < num_scores; i++)
  6.         {
  7.          in_file >> scores[i];
  8.  
  9.         }
  10.  
  11. }
  12.  
Then make the data private and the function public:

Expand|Select|Wrap|Line Numbers
  1. struct records{
  2.      private:
  3.         string name;
  4.         float quizes[7];
  5.         float projects[6];
  6.         float exams[2];
  7.         float labs[14];
  8.      public:
  9.          void get_scores(ifstream& in_file, int num_scores, float scores[]);
  10.  
  11. };
  12.  
Re-compile and verify everything is still working.

Finally, just change struct to class and tou are done.

Expand|Select|Wrap|Line Numbers
  1. class records{
  2.      private:
  3.         string name;
  4.         float quizes[7];
  5.         float projects[6];
  6.         float exams[2];
  7.         float labs[14];
  8.      public:
  9.          void get_scores(ifstream& in_file, int num_scores, float scores[]);
  10.  
  11. };
  12.  
You can now start removing function arguments that are member data.

Finally, add your constructors.

It turns out in C++ that there really are no classes. The underlying implementation is a struct with public/private/protected members. In fact, the only differende between a struct and a class is that the DEFAULT access spoecificer for a struct is public whereas the default for a class is prviate. If you specify public/private/protected for each of your struct members, then there is no difference between a struct and a class.
May 12 '07 #2
You can now start removing function arguments that are member data.

Finally, add your constructors.

It turns out in C++ that there really are no classes. The underlying implementation is a struct with public/private/protected members. In fact, the only differende between a struct and a class is that the DEFAULT access spoecificer for a struct is public whereas the default for a class is prviate. If you specify public/private/protected for each of your struct members, then there is no difference between a struct and a class.[/quote]

if I remove the arguments in my functions that are member data how will my code work, would I just have to not use functions?
May 14 '07 #3
if I remove the arguments in my functions that are member data how will my code work, would I just have to not use functions?

if my member arrays are private and I have a function that will add the values to my arrays. how can I then pass those values on to the other functions that need them or am I able to do that. ..Im really not sure of how to implement what I'm trying to do.
May 14 '07 #4
i guess my problem is that since my input is coming from a file Im having a hard time figuring out how to code that for a class since I can just set the values of my string and arrays at the beginning. And after I set the values in my class array how would I pass the values to the other functions that need them?
May 14 '07 #5
weaknessforcats
9,208 Expert Mod 8TB
Let's start at this point:
Expand|Select|Wrap|Line Numbers
  1. //function that takes in parameters to input scores in array
  2. void records::get_scores(ifstream& in_file, int num_scores, float scores[])
  3. {
  4.  
  5.         for (int i = 0; i < num_scores; i++)
  6.         {
  7.          in_file >> scores[i];
  8.  
  9.         }
  10.  
  11. }
  12.  
Here the target array is a private member of the class. To load the projects array write a member fuction to load it using the above function as a pattern:
Expand|Select|Wrap|Line Numbers
  1. //function that takes in parameters to input projects in array
  2. void records::set_projects(ifstream& in_file)
  3. {
  4.  
  5.         for (int i = 0; i < 6; i++)
  6.         {
  7.          in_file >> projects[i];
  8.  
  9.         }
  10.  
  11. }
  12.  
You don't need the pointer to the array because this function only does the projects array and you don't need the number of elements in the array becuse you have hard-coded the 6 in the class definition. Just create a member function to load each of your arrays and other member functions to access the array members.

I realize that you will have several functions that are mostly identical exceot fior the array name and the array size.
May 14 '07 #6
okay I got that now lets say i have created these

Expand|Select|Wrap|Line Numbers
  1. public:
  2.         void set_name(ifstream& in_file);
  3.         void set_quizes(ifstream& in_file);
  4.         void set_projects(ifstream& in_file);
  5.         void set_exams(ifstream& in_file);
  6.         void set_labs(ifstream& in_file);
and this is the one for the string member

Expand|Select|Wrap|Line Numbers
  1. void records::set_name(ifstream& in_file)
  2. {
  3.         in_file >> name;
  4. }
I then want to pass the string to another function to output it in a display.
I have loaded the array values but how can they be used by another function?

is it by passing records::quizes as an argument
May 14 '07 #7
weaknessforcats
9,208 Expert Mod 8TB
The "another function" will have to be a member function since the arrays are private. So you have:

Expand|Select|Wrap|Line Numbers
  1. void records::show_projects()
  2. {
  3.       for (int i = 0; i < 6; i++)
  4.         {
  5.          cout << projects[i];
  6.  
  7.         }
  8.  
  9. }
  10.  
This will show all 6 projects.

If you need the value of a specific project, then you need a member function for that purpose:

Expand|Select|Wrap|Line Numbers
  1. float records::get_project(int val)
  2. {
  3.       //might be good to check val between 0 and 5 here to avoid a crash
  4.       return projects[val]; 
  5. }
  6.  

That is, no function outside the class has access to the array. Those external functions call member functions of records to get the information you need. The idea is that the member functions will protect the projects array and keep it from getting screwed up.
May 14 '07 #8
so for the most part the functions that need to use my class members should go in the public part. and then the other functions should be okay
May 14 '07 #9
weaknessforcats
9,208 Expert Mod 8TB
The public functions are the class interface (an API if you will). These functions protect the private data from hackers an other evildoers. They also have the advantage that should the class need to be redesigned (which happens a lot) and if you can keep the function prototypes unchaned, then the only functions needing modification will be the member functions. To use your new design the class customers would only need to recompile.

This is why you are to never have public data.

Now, a function needing access to private data is out of luck unless there is a class member function that can provde the necessary data. You just don't put any old function inside the class.

So here is a function to display the project values:

Expand|Select|Wrap|Line Numbers
  1. //num is the project to display:
  2. void display_projects(records* obj, in num)
  3. {
  4.       for (int i = 0; i < 6; i++)
  5.         {
  6.          cout << i << ". " << obj-> get_project(i);
  7.  
  8.         }
  9.  
  10. }
  11.  
This line:

obj-> get_project(i);

is the call to the member function

int records::get_project(int value);

You DO NOT put the display_projects function in the records class as a member.
May 14 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

26
by: phoenix | last post by:
Hello, I've got a design question. I need to keep track of some variables and I am planning to put them inside a class or struct. Basically I'm talking about 10 bools, 20 ints and 2 arrays of...
19
by: Xandau | last post by:
hello all, i wotk with java every day but last time i have interested in C#. everything goes great except one thing... in java everything is a reference (except plain types) so i thought that...
3
by: Flip | last post by:
I'm coming from the java world, so I'm sorry if this is a simplistic question. I've read enough to be dangerous :< and would like a quick overview. In java, everything with implemenation is...
5
by: Brian | last post by:
I am "learning" C# and have run into a problem that, though I can work around it, I would like to know what the *right* way to handle the issue is. I have created an "Info" struct and assigned...
24
by: Kalpesh | last post by:
Hello All, Please help validate this design problem Assume that I have several entities in my project (eg Supplier, Customer etc). All of them save several common properties - name, address,...
24
by: arcticool | last post by:
I had an interview today and I got destroyed :( The question was why have a stack and a heap? I could answer all the practical stuff like value types live on the stack, enums are on the stack, as...
61
by: Marty | last post by:
I am new to C# and to structs so this could be easy or just not possible. I have a struct defined called Branch If I use Branch myBranch = new Branch(i); // everything works If I use Branch...
7
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are...
10
by: colin | last post by:
Hi, I profile my code and find its spending a lot of time doing implicit conversions from similar structures. the conversions are mainly things like this class Point { implicit conversion...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.