I got an input file like this.
MNSD sjs 20 30 40 50 60 70 85 97 50
abcd efgh 10 20 30 40 50 60 70 80 90 10
one two 79 50 78 20 64 54
the format should be
word word # # # # # # # # # #
(two words and ten numbers)
there is only one space for each # or word.
I have to get the average from each line and show it at the end of each line.
If there are some number missing, I have to replace it with 0.
My program allow me to output the average if there is no number missing.
I have no idea what should I do if there are some number are missing.
I was thinking to count how many ' ' before '\n' to change the number of for loop, but it only works for first line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void file_checking(ifstream& fin, ofstream& fout);
//Check the file is failing to open or not.
void get_grade(ifstream& fin, ofstream& fout);
//Get the value and calculate the aveage.
int main()
{
ifstream fin;
ofstream fout;
file_checking(fin,fout);
get_grade(fin,fout);
return 0;
}
void file_checking(ifstream& fin, ofstream& fout)
{
fin.open("before.txt");
if(fin.fail())
{
cout << "Input file opening fail.\n";
exit(1);
}
fout.open("after.txt");
if(fout.fail())
{
cout << "Output file opening fail.\n";
exit(1);
}
}
void get_grade(ifstream& fin, ofstream& fout)
{
int space,test;
double ave,value;
char next;
space = 0;
ave = 0;
fin.get(next);
while(! fin.eof())
{
fout.put(next);
fin.get(next);
if(next == ' ')
space = space + 1;
else
space = space;
if(space == 2)
{
for(int x=0;x<10;x++)
{
fout << " ";
value = 0;
fin >> value;
fout << value;
ave = ave + value;
space =0;
}
ave = ave /10;
fout << " ";
fout << ave;
}
else
ave =ave;
}
}
|