-2

I have already created a file called ( student.txt) and i put the following information inside the file

Will Smith 99
Sarah Johnson 100 
Tim Howard 70 
Francesco Totti 95 
Michael Jackson 92

I want to ask the user to enter the file name,once they enter the file name, I want to displays the average score by reading the data from the file.

Note : Each line in the file contains the first name, last name, and test score of a student.

Here's what i did so far and this could only display what inside the file Please help me to declare the file name and to display the average score of a student

#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:
}

1 Answers1

0

Assuming that all entries will be formatted like you specified, you could implement some version of this (this is not written perfectly, but it gives the general idea):

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;

To get the file name from the user at the beginning, use

string studentfilename;
cout << "Enter student file name: ";
cin >> studentfilename;

Good luck!

Umm_Me
  • 16
  • 4