I was asked to calculate the average of marks for 10 students. First, I was able to read and retrieve the data from data.txt file which looks like this:
No. Name Test1 Test2 Test3
1 Ahmad 58 97 83
2 Dollah 78 76 70
3 Ramesh 85 75 84
4 Maimunah 87 45 74
5 Robert 74 68 97
6 Kumar 77 73 45
7 Intan 56 23 27
8 Ping 74 58 18
9 Idayu 47 98 95
10 Roslan 79 98 78
Then I have to calculate the average for each student and determine the grades.
Here are what I've done so far.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
ifstream inFile1;
string temp;
int line=0;
inFile1.open("data.txt");
if(inFile1.fail())
{
cout << "File cannot be opened" << endl;
exit(1);
}
while(getline(inFile1, temp))
{
line++;
}
inFile1.close();
return 0;
}
This program should at least consists two prototype function: average() and grade(). This is where I got stuck.
You can check the answers here: find average salaries from file in c++.
Basically when you iterate through the file lines you should split the
temp
string into tokens you are interested in. How? An option would be to usegetline
with the delimeter' '
or look into thestd::noskipws
stream manipulator or simply useoperator>>
to read from the file - depends on the details of your requirements.If I correctly understand your case, I'd go with the
operator>>
to get the name of the student and then read usinggetline(inFile, gradesText)
to read until end of line to get all grades for the current student.Then I'd use a separate function to split the strings into a vector of grades. How to do the splitting you can check in Split a string in C++?. This way you could prepare a function like
vector<int> split(const string& line, char delim = ' ')
. Within the implementation you should probably usestd::stoi
for the string-to-int conversion.Afterwards, when you already have a proper collection you can calculate the mean from it with: