Sum/Average from input file to output file

Read floating values from the file inputfile.txt and write the sum,average,and number of valid input values to the output file outputfile.txt. I have most of it figured out, I am just struggling with the while loop, any help is appreciated.
Input file: 8.9 2.6 5.3
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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    cout  << fixed  << showpoint;

    float val;
    float sum = 0;
    float average = 0;
    int count = 0;
    ifstream inData;			
    ofstream outData;			

    inData.open("inputfile.txt");
    if (!inData)
    {
       cout << "Can't open the input file successfuly." << endl;
       return 1;
    }
   
    outData.open("outputfile.txt");

    if (!outData)
    {
       cout << "Can't open the output file successfuly." << endl;
       return 2;
    }

    cout  << "The initial value for count is " << count  << ".  " << endl;
    cout << "Starting to process input file ... " << endl;

    inData >> val;  
    while (inData)  
    {
       sum = sum + val;
       count++;
       inData  >> val;	
    }

    if (count != 0 )
        average = sum / count;
    else
	average = 0;

    outData  << "The sum of the input values is " << sum  << "." << endl;
    outData  << "The number of valid input values is " << count  << "." << endl;
    outData  << "The average is " << average << "." <<endl;   
    cout << "Output has been placed in the file: outputfile.txt" << endl;
    return 0;
}
Last edited on
Please Edit your post and put all the code between code tags <>, they are under the format section.

Also please post what you have in your text file.
Sorry, I'm new to the site
Its alright! So...

It looks like your file consists of 3 decimal numbers. So you want to use float/double.

This Video should help you - https://www.youtube.com/watch?v=iGWhPwh3n-o&ab_channel=thenewboston

What you want to do is basically.

Create a variable.

float number;

Then in that while-loop. Read in one number (Just like he does in the video) and then put all the numbers in sum, and increase "count" each loop.

Why dont you start off with this. And then post your new code and I'll help you out if you got trouble :)

I got it, thanks for the help!
Did you manage to get all of the program to work?

Edit: Looks like you did, congrats :)
Last edited on
Topic archived. No new replies allowed.