My question is, we were given a homework assignment and it comes with a .txt file that we need to read and then sort.
The .txt file has scores on it like this:
78
80
97
45
60
...
...etc...etc...
What I'm trying to figure out is how can I find the average and other math equations with these. We haven't learned arrays or vectors yet so I can't use them. Would I assign each one a variable? no? Any help would be beneficial to me! Thanks!
your topic should match your question. "Read text file" gives impression of "difficulties in reading text file".
As Esslercuffi said, average = accumulator/counter
There's many questions like this, I would try searching if you want a solution.
That being said, this is still easy to do without having to store the values in an array.
You just need to calculate the sum as you go.
The [my stream] >> [my variable] operator will store the next number in the file into a variable. You just need to keep track of the sum, incrementing it by the value each time, while also keeping tracking of how many numbers you've added so far.
Then divide the total sum by that number.
as a start:
1 2 3 4 5 6
std::ifstream f("file.txt")
double n;
while (f >> n)
{
std::cout << n << " ";
}
will print every number in your file.
The ifstream type is in the <fstream> C++ header.