Well, you could do it like this:
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
ifstream students("students.txt");
ifstream grades("grades.txt");
ofstream report("report.txt");
string firstname, lastname, letter_grade;
int test1, test2, test3;
double average;
report << "Student's Name" << "\tStudent's Grade" << endl;
while(students >> firstname >> lastname)
{
grades >> test1 >> test2 >> test3;
average = (test1 + test2 + test3) / 3.0;
if (average==100){
letter_grade="Teacher too easy";
}
else if (average>=90){
letter_grade="A";
}
else if (average>=80){
letter_grade="B";
}
else if (average>=70){
letter_grade="C";
}
else if (average>=60){
letter_grade="D";
}
else {letter_grade="F";}
report << lastname << "," << firstname << "\t" << average
<< " (" << letter_grade << ")" << endl;
}
students.close();
grades.close();
report.close();
return 0;
}
|
Output:
Student's Name Student's Grade
Forest,Daniel 46.6667 (F)
Wong,Michelle 62.3333 (D)
Hass,Derek 79.3333 (C) |
Ideally I think I'd want to put the calculation for the letter grade into a function which you call for each student, rather than have all those "if"s in the main loop, but I don't know if you've learned anything with functions yet.
Also, not quite sure if I got the numbers exactly right for the letter-grade calculation, but I'm sure you get the drift and can change it easily enough.
Things you should ideally still do:
(a) put code in to check that the files don't fail to open
(b) use features of <iomanip> to format the report output, rather than just use tabs
P.S. The code below shows why you needed to change the line which calculates the average:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
int main()
{
double average;
int a=10, b=20, c=30;
average= a + b + c / 3;
std::cout << average << std::endl;
// this gives average as 40, which is wrong
average= (a + b + c) / 3;
std::cout << average << std::endl;
// this gives average as 20, which is correct
}
|
Division has a higher order of precedence than addition, so in the first example the program first calculates c/3 (which is 10) and then adds it to a+b which comes to 40. In the second example, by putting a+b+c in parentheses, it adds them together first (which gets 60) and then divides the 60 by 3 to get 20.
Hope that helps. Good luck.