0

I have a problem where I have to read in a text file. Take each line of numbers, average the numbers, and then push those numbers to a vector.

70 79 72 78 71 73 68 74 75 70

78 89 96 91 94 95 92 88 95 92

83 81 93 85 84 79 78 90 88 79

This is only some of the file. I don't know how to put all of it, I am sure it is not necessary.

I have successfully opened the file. I have looked everywhere online about how to read in each line and try to average the numbers. However I have always ended up unsuccessful in doing that. I am a beginner to C++ so I am very sorry for not knowing much.

How do I take each line from the file and average them in order to push it to a vector?

int main() {
    string inFileName = "lab1.txt";
    ifstream inFile;
    vector<string> scores;
    string myLine2;
    openFile(inFile, inFileName);
    getAvgofContents(inFile, myLine2);
}

void openFile(ifstream &file, string name){
    file.open(name);

    while (!file.is_open()) {
        cout << "Unable to open default file/file path.\nPlease enter a new file/file path:" << endl;
        cin >> name;
        file.open(name);
    }
    cout << "FILE IS OPEN!!!\n";
}

void getAvgofContents(ifstream &file, string line){
    while (file){
        getline(file, line);
        cout << line << endl;
    }
}

I am supposed to get results like:
73
81.5
84.1
...
...
Then after averaging each line, push the results to a vector.
Donovan Le
  • 13
  • 2
  • 1
    Possible duplicate of [Read file line by line using ifstream in C++](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – Ken White Jan 17 '19 at 03:37
  • 1
    Where does your program do the wrong thing / get stuck? Is the problem reading in the file, or finding the averages? – The Zach Man Jan 17 '19 at 03:38
  • @TheZachMan I am having a problem with finding the averages of each line. The file reads in properly, no problems with that. I'm sorry if I didn't make that clear. Thanks! – Donovan Le Jan 17 '19 at 19:55

1 Answers1

1

This may help:

float getAvgOfLine(string line) {
  float total = 0;
  int count = 0;
  stringstream stream(line);
  while(1) {
   int n;
   stream >> n;
   if(!stream)
      break;
   total += n;
   count++;
  }
  if (count == 0) {
     // the line has no number
     return 0;
  }
  return total/count;
}

float getAvgofContents(ifstream &file, string line){
    float total;
    int number;
    while (getline(file, line)){
        cout << getAvgOfLine(line)<< endl;
    }
}

Reference: Convert String containing several numbers into integers

truongminh
  • 26
  • 4