Write your question here.
Hello! I am having trouble finding out how to read a file and find an average for the 10 rows of numbers. I already have the file opened, but I do not know the right commands to proceed. The text file name is "lab1.txt". I then need to store the 10 averages in a vector to use later in the program.
Just read 10 numbers, summing them up, and divide by 10. Do that 10 times, storing the results in your vector.
1 2 3 4 5 6 7 8 9 10 11 12
vector<double> averages;
for (int i = 0; i < 10; ++i)
{
int sum = 0;
for (int j = 0; j < 10; ++j)
{
int n;
fin >> n;
sum += n;
}
averages.push_back(sum / 10.0);
}
...
std::vector<double> v_averages; // instantiates an empty vector
std::string tmp;
while ( std::getline( my_file, tmp ) ) // reads a whole line
{
std::istringstream iss( tmp ); // copies the string into
int total = 0;
int number;
while( iss >> number ) // extract the numbers
{
total += number;
}
v_averages.push_back( total / 10.0 ); // appends the average to the vector
}
...