Search code examples
c++ifstream

How do I take each line from a text file and average them?


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.

Solution

  • 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