所以在我的作业中,我需要阅读一个文本文件,上面有学生的名字和他们的考试成绩,并在屏幕上显示平均考试分数和最高考试分数。
文本文件的内容是:
到目前为止,我的代码是:
#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“表示”highestScore“而不是"0"?
发布于 2017-11-27 07:18:27
while (myFile >> firstName >> lastName >> testScore) {
if (highestScore < testScore) {
highestScore = testScore;
}
}你为什么要再读一遍这个文件?你应该在总结的同时处理它:
while (myFile >> firstName >> lastName >> testScore) {
totalScore = totalScore + testScore;
if (highestScore < testScore) {
highestScore = testScore;
}
i++;
}或者,在尝试再次阅读之前,使用倒带文件:
myfile.clear();
myfile.seekg(0);
while (myFile >> firstName >> lastName >> testScore) {
/* stuff... */发布于 2017-11-27 07:17:58
使用第一个循环,您将一直遍历该文件直至结束。然后,它停留在最后,它不会“倒带”到开始自动。
要么您必须将http://en.cppreference.com/w/cpp/io/basic_istream/seekg返回到第二个循环的开头(并且清除为文件结束状态)。或者计算第一个循环中最高的分数。
https://stackoverflow.com/questions/47505592
复制相似问题