因此,对于我的作业,我需要阅读一个包含学生姓名和考试成绩的文本文件,并在屏幕上显示平均考试成绩和最高考试成绩。
文本文件的内容是:
我到目前为止的代码是:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void inputFile(string, string, int, int, int, int);
int main()
{
string firstName;
string lastName;
int testScore = 0;
int totalScore = 0;
int avgScore = 0;
int highestScore = 0;
inputFile(firstName, lastName, testScore, totalScore, avgScore, highestScore);
system("pause");
return 0;
}
void inputFile(string firstName, string lastName, int testScore, int totalScore, int avgScore, int highestScore)
{
ifstream myFile("scores.txt");
int i = 0;
while (myFile >> firstName >> lastName >> testScore) {
totalScore = totalScore + testScore;
i++;
}
avgScore = totalScore / i;
cout << "Average score: " << avgScore << endl;
while (myFile >> firstName >> lastName >> testScore) {
if (highestScore < testScore) {
highestScore = testScore;
}
}
cout << "Highest score: " << highestScore << endl;
}
当我运行程序时,它会正确显示平均分数,但是当达到最高分时,它每次只显示“0”而不是显示“100”,这是文本文件中的最大数字。如何让它显示“100”代表“最高分数”而不是“0”?
答案 0 :(得分:1)
答案 1 :(得分:1)
while (myFile >> firstName >> lastName >> testScore) {
if (highestScore < testScore) {
highestScore = testScore;
}
}
您为什么要再次尝试阅读该文件?您应该在总结的同时处理它:
while (myFile >> firstName >> lastName >> testScore) {
totalScore = totalScore + testScore;
if (highestScore < testScore) {
highestScore = testScore;
}
i++;
}
或者,在尝试再次阅读之前rewind the file:
myfile.clear();
myfile.seekg(0);
while (myFile >> firstName >> lastName >> testScore) {
/* stuff... */