Search code examples
c++if-statementwhile-loopiofstream

Read multiple line in text file and write in another text file


Here is my scores.txt file

7 2 11 4
9 1 30 3
5 3 20 3
10 1 10 2
5 0 50 0

This is a detais of 5 cricketer match inning

structure for above details:

In text file first column represent 7-overs, 2-maiden, 11-runs, 4-wickets.

I want to get five bowlers(count the column) in the text file and average(third column value divide by the fourth column) of that bowlers and print/display in the terminal.

like below:

Bowler    Average
1         2.75
2         10
3         6.66
4         5
5         NA
6         NA

above file has six bowlers but last one is repeated.I tried fix it to only five times because scores.txt file has five lines.

Here is my code

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
using std::setw;

int main(){
    float avg;
    int over,maiden,runs,wickets;
    ifstream scores;
    scores.open("scores.txt");
    if(!scores){
        cout<<"Error \n";
        return -1;
    }

    ofstream average("average.txt");
    if(!average){
        cout<<"Error \n";
        return -1;
    }

    average << "Bowler"<<"\t"<<"Average"<<endl;
    int i=1;
    //scores >> over >> maiden >> runs >> wickets;
    while(!scores.eof()){
        scores >> over >> maiden >> runs >> wickets;
        avg = runs/float(wickets);
        if(wickets == 0){
            average<<i<<"\t"<<"NA"<<endl;
        }else{
            //avg = runs/float(wickets);
            average << i<<"\t"<<avg<<endl;

        }
        i++;
    }
    scores.close();
    average.close();
    return 0;
}

Solution

  • I think your problem is this line

    while(!scores.eof()){
    

    When you have read the last line, scores.eof() is false, you try to read another line, the reading fail (and scores.eof() become true), you don't test if the reading is with or without error and you use two times the values of the last line.

    I suggest something like

    while( scores >> over >> maiden >> runs >> wickets ){
        avg = runs/float(wickets);