【问题标题】:How to display the largest number from a text file properly?如何正确显示文本文件中的最大数字?
【发布时间】: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


【解决方案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... */

【讨论】:

    【解决方案2】:

    在第一个循环中,您将遍历文件一直到最后。然后一直停留在结尾,不会自动“倒回”到开头。

    您必须 seek 回到第二个循环的开头(以及 clear 文件结束状态)。 或者也计算第一个循环中的最高分。

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多