0

I need to take an unknown number of integers in a file and store them into a vector, sort from greatest to least and find the harmonic mean of the smallest and largest number. I then need to output the mean and all the numbers in the file into a new file. I created a code that worked perfectly for integers less than ten but it input the numbers into the vector as strings and I need to rewrite the code to input each line of the file as an integer but am getting errors. It will not output anything to "AverageFile" and the program will crash after loading. It gives the error

"terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"

My code is below, I think the problem is with either input or output of the vector.

#include <iostream>
#include <fstream>
#include <string>
#include<stdlib.h>
#include<vector>
using namespace std;

int main()
{
    int line;
    vector<int> score;
    int i=0;
    //double sum=0;
    //double avg;
    int temp=0;

    string x;
    cin>>x;
    ifstream feederfile(x.c_str()); 

    if(feederfile.is_open())
    {
        while(feederfile.good())
       {
          score.push_back(line);
          i++;
       }

       feederfile.close();
    }
    else cout<<"Unable to open Source file";

    //Sorting from greatest to least:
    for(int i=0;i<score.size()-1;i++)
    {
      for(int k=i;k<score.size();k++)
      {
        if(score[i]<score[k])
        {
            temp=score[i];
            score[i]=score[k];
            score[k]=temp;
        }
      }
    }

    int a=score[score.size()-1];
    int b=score[0];
    double abh=2/(1/double (a)+1/double (b));
    ofstream myfile ("AverageFile.txt");

    if(myfile.is_open())
    {
        myfile<<"The Harmonic Mean is: "<<abh<<endl;
        myfile<<"Sorted Numbers: ";
        for(int i=0;i<score.size();i++)
        {
            if(i<score.size()-1)
            {
                myfile<<score[i]<<", ";
            }
            else{myfile<<score[i];}
        }
    myfile.close();
    }
    else cout<<"Unable to open Export file";
    return 0;
}
Uncblueguy
  • 33
  • 5

1 Answers1

4

You forgot to read from the file. In

while(feederfile.good()){
    score.push_back(line);
    i++;
}

You never read from the file so you have an infinite loop as the file will always be good() and eventually you run out of memory trying to add objects into the vector.

Using feederfile.good() is not what you want to use for your condition. Instead you want to make the read operation the loop condition. So if we do that then we have

while(feederfile >> line){
    score.push_back(line);
    i++;
}

Which will read until it encounter an error or the end of file.

Community
  • 1
  • 1
NathanOliver
  • 150,499
  • 26
  • 240
  • 331