Using streams:
double calculateGPA() {
double credit_sum = 0.0, grade_sum = 0.0;
double credit, grade;
ifstream reader("grades.txt");
while (!reader.eof()) { /* while the file still has numbers to be read */
reader >> credit >> grade;
if (reader.fail()) {
/* something unexpected happened (read error/formatting error) */
break;
}
credit_sum += credit;
grade_sum += grade;
}
if(credit_sum == 0.0) {
/* avoid divide by zero */
return 0.0;
}
/* divide the total grade by the total credits */
return grade_sum / credit_sum;
}
Notes:
- Assumes .txt file just has numbers (credits, grade, credits, grade, ...) delimited by whitespace (spaces or line breaks): For more complicated formatting you want scanf or regex.
- Returns double instead of float, you usually want double's precision over float's relatively small speed and memory advantage.
- File will be closed at the end of the function, when reader goes out of scope. reader.close() is not necessary, but wouldn't be a bad thing to put in (I'm just lazy.)