Streamlining code

Hello. I'm trying to read 4 sets of numbers from a file, sum them, average them and assign them a grade. This is what I have so far and it seems to be working for the first set just fine. My question is how would I go about streamlining this for the 12 other sets of numbers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    ifstream studentGrades;
    int stuGrad1, stuGrad2, stuGrad3, stuGrad4, sum1;
    int stuLetterGrade1;
    char letterGrade1;

   studentGrades.open("grades.txt"); 

   studentGrades>>stuGrad1>>stuGrad2>>stuGrad3>>stuGrad4;  

   sum1=stuGrad1+stuGrad2+stuGrad3+stuGrad4; 
   stuLetterGrade1=sum1/4; 

        if (stuLetterGrade1 >= 90)  
            letterGrade1='A';
        else if (stuLetterGrade1 >= 80)
            letterGrade1='B';
        else if (stuLetterGrade1 >= 70)
            letterGrade1='C';
        else if (stuLetterGrade1 >= 60)
            letterGrade1='D';
        else if (stuLetterGrade1 >= 50)
            letterGrade1='F';

   cout<<"...........Student's Grades......Grade Average...Letter Grade.........\n";
   cout<<"Student 1: "<<stuGrad1<<" "<<stuGrad2<<" "<<stuGrad3<<" "<<stuGrad4;  
   cout<<" \t\t "<<sum1/4<<" \t\t "<<letterGrade1<<"\n"<<endl;

    return 0;
}


The remaining sets are:

44 55 77 88 (first set)
79 88 100 99
77 99 98 99
100 88 89 100
55 56 40 77
100 100 99 95
88 84 87 88
96 97 99 100
30 44 77 55
79 77 88 0
54 52 60 77
88 77 88 77
44 77 10 95

Thanks :)
- Try to include the lines 16 - 34 inside of a while or a do...while loop controlled by the End Of File.
- Before return 0; don't forget to close the file.
Last edited on
Awesome, thank you so much Condor! Figured it out with your help. :)
@condor by chance have you heard of RAII? The file is closed automatically when it goes out of scope, there is no reason to close it manually unless you will be reusing it for some strange reason (and even then you would move-assign a new file instead).

Also, you should not loop until end of file - you should perform the input in the loop condition. Otherwise you may get garbage values the last time around.
Last edited on
@L B
You are perfectly right. Thank you!
Topic archived. No new replies allowed.