因此,对于我的作业,我需要读取一个包含学生姓名和考试成绩的文本文件,并在屏幕上显示平均考试成绩和最高考试成绩。
文本文件的内容是:
- 约翰·史密斯 99
- 莎拉·约翰逊 85 岁
- 吉姆罗宾逊 70
- 玛丽·安德森 100
- 迈克尔· jackson 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”?
最佳答案
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... */
关于c++ - 如何正确显示文本文件中的最大数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47505592/