从文件的一行中查找数字的平均值,避免使用第一个单词

Finding average of numbers from one line of a file avoiding the first word

本文关键字:平均值 单词 第一个 数字 查找 文件 一行      更新时间:2023-10-16

我有一个具有以下格式的文本文件:

U123 78 90 65 85

U234 87 98 90 56

U345 89 90 98 87

U456 45 56 67 78

第一个值 (Uxxx( 是"学生编号",同一行上的所有其他值都是考试成绩(第一个是考试 1,第二个考试 2,依此类推(

我正在尝试获取特定学生(由用户指定(的所有考试的平均值,但在如何存储特定行的考试值方面遇到问题。

我有一个不同的功能,可以显示指定学生的分数,并正在尝试对其进行修改以使其也为此工作,但遇到了麻烦。以下是该函数的代码:

void DisplayStudentScores()
{
    string stuNum;
    ifstream inFile;
    inFile.open(scores.txt);
    //for testing purposes
    if(!inFile)     {
        cout << "File not found" << endl;
        exit(1);
    }
    //end of test
    cout << "Enter the Student ID of who's scores you would like to see: ";
    cin >> stuNum;
    cout << endl;
    string line;
    while(getline(inFile, line)){
        if(line.find(stuNum) != string::npos){
            cout << line << endl;
            break;
        }
        else{
            cout << "Student not found" << endl;
            break;
        }           
    }
}
字段用

空格整齐地分隔,因此流运算符比getline更好:

string stu;
int score1, score2, score3, score4;
infile >> stu >> score1 >> score2 >> score3 >> score4;

你可以把它放在一个循环中:

while(infile >> stu >> score1 >> score2 >> score3 >> score4){
  if(stu == stuNum){
    // calculate and print average
    return;
  }
}
cout << "Student " << stuNum << " not found" << endl;