Search code examples
c++c++11text-filesfilestreamifstream

Read 11th coloumn of numbers from a file and average it?(c++)


Its my beginners c++ assignment, I have a file of 12 columns of numbers and having 50 rows.

I am asked to find the average of the 11th column of the numbers and display it on the standard output.

Its a beginners class so NO advanced topics like vectors are allowed .

I was trying to make 12 variables for each coloumn and use the while loop to read the 11th coloumn but can't figure out how to add all the numbers of 11th coloumn into that variable.

The while loop I used was like this:

while(inputfile >> col1 >> col2>> col3>> col4>> col5>> col6>> col7>>
     col8>> col9>> col10>> col11>> col12 ) 
{ cout<< col11 << endl; }

Side note : all the col above are int variables. And inputfile is the ifstream file object

The above loop would print out the whole coloumn 11 but I can't figure out how to add the whole coloumn 11 of 50 rows (i.e 50 numbers) to find the average(divide the total by 50)

The above method might be wrong too

Any help in this matter will be appreciated.

Hopeful of a response soon.

Thanks in advance. :)


Solution

  • Since the only answer is wrong, and the comment perhaps missing a vital clue...

    You need to keep a running total of the column 11 values. I'd also keep track of the count, although in your case you could just skip that and hard-code the value 50. So the bits you need are:

    int total = 0;
    int count = 0;
    

    Then in your read loop:

    while (...) {
        total += col11; // keep a running total
        ++count; // add 1 to count
    }
    

    Then to calculate the average, you divide one by the other.

    But, this is a little tricky. If you do it directly, you divide one int by another int, and get the result truncated to an int. E.g. 1/2 would give you 0, which is not what you mean (0.5).

    You need to use a cast to turn at least one of the values into a double before the division is done:

    double average = static_cast<double>(total) / count;
    

    See full code here.

    Other ways around the division problem would be to store total or count as a double in the first place, although I find that misleading as they are really integers, or if you are sticking with using 50 directly, you could just do average = total / 50.0 (50.0 is a double value).

    Since you are a beginner, I'll also take a moment to advise you against using namespace std; and use of endl, not just for performance reasons, but also to make the code clearer by separating the unrelated actions of writing a newline and flushing a stream.