This is my version of your program. It is not exactly similar, but hopefully it will help you.
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
int grade;
int total;
int grade_count;
int second_space;
double average;
string line;
string name;
string average_string;
ofstream output("output.txt", ios::out);
ifstream input("input.txt", ios::in);
if(!input){
cerr << "Error opening input.txt...";
cin.get();
exit(1);
}
output << "Name" << setw(34) << "Grade average\n" << endl;
while(!input.eof()){
getline(input, line);
second_space = line.find_first_of(' ', line.find_first_of(' ') + 1);
istringstream iss(line.substr(second_space));
name = line.substr(0, second_space);
average = 0;
grade_count = 0;
total = 0;
while(iss >> grade){
grade_count++;
total += grade;
average = static_cast<double>(total) / grade_count;
}
ostringstream oss;
oss << average;
average_string = oss.str();
output << name << setw(24 - name.length() + average_string.length()) << average << endl;
}
input.close();
output.close();
cout << "Grade averages were successfully calculated and saved to output.txt" << endl;
cin.get();
return 0;
}
This is the input file:
Code:
Smith John 75 86 72 90 66 82 95 57 88 80
Peterson Mary 65 80 78 91 76 72 90 50 87 85
Dalton Nick 55 46 79 98 68 82 99 87 58 100
Robinson Carla 83 76 32 80 96 62 95 77 98 81
Hamilton Petter 45 76 71 90 61 89 94 58 68 89
Gilbert Jeffrey 72 83 74 95 67 86 98 59 80 77
Bush John 95 96 82 69 76 82 95 97 98 90
And this is the output file:
Code:
Name Grade average
Smith John 79.1
Peterson Mary 77.4
Dalton Nick 77.2
Robinson Carla 78
Hamilton Petter 74.1
Gilbert Jeffrey 79.1
Bush John 88
If you have any questions, don't resitate to ask
Bookmarks