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

标签 c++ text-files

因此,对于我的作业,我需要读取一个包含学生姓名和考试成绩的文本文件,并在屏幕上显示平均考试成绩和最高考试成绩。

文本文件的内容是:

  • 约翰·史密斯 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/

相关文章:

c++ - QML 和 C++ 属性 - ReferenceError : Can't find variable

vb.net - 有没有更好的方法来计算文本文件中的行数?

python - Pandas read_csv : Data is not being read from text file (open() reads hex chars)

c++ - 如何从 .t​​xt 文件中读取带有符号 "/"和 ":"的生日?

c++ - 将 MBCS 和 Unicode 库链接在一起

c++ - RVO应该什么时候启动?

c++ - 确定某人是否硬连接到 C++ 中的路由器

c++ - 错误 C2039 : 'vector' : is not a member of 'std'

python - 在 Python 中调试问答游戏

使用 .htaccess 处理 PHP 错误并写入 php_error.log 文本文件