我已经创建了一个名为(student.txt)的文件,我将以下信息放在文件
中Will Smith 99
Sarah Johnson 100
Tim Howard 70
Francesco Totti 95
Michael Jackson 92
我想让用户输入文件名,一旦输入文件名,我想通过从文件中读取数据来显示平均分数。
注意:文件中的每一行都包含学生的名字,姓氏和考试成绩。
这是我到目前为止所做的,这只能显示文件内部的内容 请帮我声明文件名并显示学生的平均分
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string studentFile;
ifstream file("student.txt");
if (file.is_open()) {
while (getline(file,studentFile))
{
cout << studentFile << '\n';
}
file.close();
}
system("pause");
return 0:
}
答案 0 :(得分:0)
好开始。只有唠叨是你应该避免using namespace std;
。请在此处阅读原因:Why is "using namespace std" considered bad practice?
关于主题,最简单的方法是:
在输入循环之上定义跟踪学生标记所需的变量
int numberOfStudents = 0;
int sum = 0;
在循环内部添加代码以分割读取行并获得学生的标记
std::string firstname;
std::string lastname;
int mark;
// create a new stream that is just the input line and split it into firstname,
// lastname and mark.
std::stringstream linestream(studentFile);
// this next line might look a bit wierd. When reading from a stream, always check whether
// or not the read succeeded. The next line will attempt to read in three things and
// if any one of reads failed the whole operation fails. How you handle s bad line
// is up to you
if (linestream >> firstname >> lastname >> mark)
{
sum += mark;
numberOfStudents ++;
}
在循环下计算平均值
double average = (double) sum / (double)numberOfStudents;
最后打印结果。
有许多更好,更快的方法可以做到这一点,但以上是写作最快,最容易解释的。
答案 1 :(得分:0)
假设所有条目的格式都与您指定的一样,您可以实现一些版本(这不是完美的写,但它提供了一般的想法):
string line;
float total_grade = 0;
int num_grades = 0;
while (getline(file, line)) {
//ignore everything up to score
int number_position = line.find_last_of(" ") + 1;
string grade_string = line.substr(number_position, line.length() - number_position);
//turn string of score into number
float grade = stof(grade_string);
total_grade += grade;
num_grades++;
}
float average_grade = total_grade / num_grades;
要从头开始获取用户的文件名,请使用
string studentfilename;
cout << "Enter student file name: ";
cin >> studentfilename;
祝你好运!