【发布时间】:2017-11-28 23:36:15
【问题描述】:
因此,对于我的作业,我需要阅读一个包含学生姓名及其考试成绩的文本文件,并在屏幕上显示平均考试成绩和最高考试成绩。
文本文件的内容是:
- 约翰·史密斯 99
- 莎拉·约翰逊 85
- 吉姆·罗宾逊 70
- 玛丽安德森 100
- 迈克尔杰克逊 92
我目前的代码是:
#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”,这是文本文件中的最大数字。我如何让它为“highestScore”显示“100”而不是“0”?
【问题讨论】:
-
在与您的问题完全无关的注释中,为什么您将变量作为参数传递给
inputFile函数?为什么不简单地将它们定义为inputFile函数中的局部变量?
标签: c++ text-files