首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确显示文本文件中的最大数字?

如何正确显示文本文件中的最大数字?
EN

Stack Overflow用户
提问于 2017-11-27 07:15:19
回答 2查看 96关注 0票数 0

所以在我的作业中,我需要阅读一个文本文件,上面有学生的名字和他们的考试成绩,并在屏幕上显示平均考试分数和最高考试分数。

文本文件的内容是:

  • 约翰·史密斯99
  • 莎拉·约翰逊85
  • 吉姆·罗宾逊70
  • 玛丽·安德森100
  • 迈克尔·杰克逊92

到目前为止,我的代码是:

代码语言:javascript
复制
#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"?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-11-27 07:18:27

代码语言:javascript
复制
while (myFile >> firstName >> lastName >> testScore) {
    if (highestScore < testScore) {
        highestScore = testScore;
    }
}

你为什么要再读一遍这个文件?你应该在总结的同时处理它:

代码语言:javascript
复制
while (myFile >> firstName >> lastName >> testScore) {
    totalScore = totalScore + testScore;
    if (highestScore < testScore) {
        highestScore = testScore;
    }
    i++;
}

或者,在尝试再次阅读之前,使用倒带文件

代码语言:javascript
复制
myfile.clear();
myfile.seekg(0);
while (myFile >> firstName >> lastName >> testScore) {
    /* stuff... */
票数 1
EN

Stack Overflow用户

发布于 2017-11-27 07:17:58

使用第一个循环,您将一直遍历该文件直至结束。然后,它停留在最后,它不会“倒带”到开始自动。

要么您必须将http://en.cppreference.com/w/cpp/io/basic_istream/seekg返回到第二个循环的开头(并且清除为文件结束状态)。或者计算第一个循环中最高的分数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47505592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档