Home > Net >  Code to take value from file and print average, max and min does not work
Code to take value from file and print average, max and min does not work

Time:11-11

I want to take a large number of different numbers from a file and give back the Average, Max, and Min values to the command line. I came so far, just to loop over the code, not further. I have tried many ways but nothing is working. Can you please guide me?

fstream my_file ("values.txt");
vector<int> nums;
double input;
// int max_value {0};
// int min_value {0};
// double average_value = accumulate(nums.begin(), nums.end(), 0) / nums.size();

while (my_file >> input)
{
    nums.push_back(input);
}

for(int num : nums){
    cout << num << endl;
}

CodePudding user response:

Your code looks OK, except for you need to accumulate after you populate your vector:

fstream my_file ("values.txt");
vector<int> nums;
double input;

while (my_file >> input )
{
  nums.push_back(input);
}
double average_value = accumulate(nums.begin(), nums.end(), 0) / nums.size();
  •  Tags:  
  • c
  • Related