Looping with an Indata file

I have a homework question. I am not sure how to write the program for.

Write a looping code segment that takes as input up to 20 integer scores from file indata, and outputs their average. If the file contains fewer than 20 scores, the segment should still output the correct average. If the file contains more than 20 scores, the additional numbers should be ignored.
We can help you when you have problems. YES. But we can't do your homework for you. I'll give you a shell though.

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
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    ifstream inFile;
    inFile.open("something.txt");
    
    
    if (!inFile) 
    {
        cout << "\n\nError! - Invalid file name!  (1)\n\n";
        system ("pause"); // this is needed depending on compiler
        return 1;
    }

    // your code goes here.

    inFile.close ();
    inFile.clear();
}


Hope this helps. Let me know if you have more questions.
Last edited on
Thanks. But how do I create the 20 integers part. That is where Im really stuck at.
you would have to do a while loop that would look kind of like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int sum = 0; 
int average, temp;
int count = 0;

while(inFile)
{
     inFile >> temp;
     sum = sum + temp;
     count++;
}

average = sum / count;


could someone double check this? Been awhile since i've had to do this.
Last edited on
@hbjgd
After having said that you won't do his/her homework, you still gave away the code!?
And as for Chan,
Are you asking how to put 20 integers in file? Open up notepad and simply type 20 numbers separated by a space. Now that isn't much hard is it?
My Bad. couldn't help it. glad the person got a good grade though =D haha
Topic archived. No new replies allowed.