0

I'm working on an assignment to assign students names and their grades to an array and find the average grade. I can't seem to get any cout statements to display after the while loop. I've been banging my head against a wall for a while so any help would be great. Probably something obvious I'm just missing. Worth the txt file has both names and their scores.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    //Variables
    ifstream inFile;
    ofstream outFile;
    inFile.open("data7.txt");
    outFile.open("Results.txt");
    int quantity = 0;
    int sum = 0;
    int x = 0;
    double avg = 0;
    double grade[MAX];
    double gradeInput;
    string name[MAX];
    string nameInput;

    //Checks if file is found
    if (!inFile)
    {
        cout << "Error finding input file\n";       
    }

    while (!inFile.eof())
    {
        x++;

        getline(inFile, nameInput);
        inFile >> gradeInput;

        name[x] = nameInput;
        grade[x] = gradeInput;
    }

    for (int i = 0; x > i;)
    {
        i++;

        inFile >> sum;
        avg = avg + sum;

        avg = avg / i;  
    }

    cout << "Enter quantity of grades to be processed (0 - , " << x << ", ):";
    cin >> quantity;
  • 4
    [Don't. Use. `eof`.](https://stackoverflow.com/q/5605125/2602718) – scohe001 Nov 15 '19 at 22:40
  • 2
    Recommended reading: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Nov 15 '19 at 22:40
  • 1
    I recommend producing a [mcve] and if that doesn't help you solve the problem, edit the question t include the [mcve]. – user4581301 Nov 15 '19 at 22:42
  • `inFile >> sum;` in the `for` loop must be wrong if you already have read the whole file in the previous `while` loop. – walnut Nov 15 '19 at 22:45
  • [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) and the above linked question about `eof()` are the source of your problem. In your first loop, `eof()` will never be set, because `fail()` bit will be set before - extraction failed because `getline` and `>>` don't mix too well. – Yksisarvinen Nov 15 '19 at 22:46
  • please post an example of data7.txt content – Berto99 Nov 15 '19 at 22:46
  • Possible duplicate of [Why is iostream::eof inside a loop condition (i.e. \`while (!stream.eof())\`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Jeeter Nov 16 '19 at 00:10

0 Answers0