2

Working on an assignment for my coding class which involves the function below, which is supposed to read quiz scores from an input file and put up to 12 of them into an array. I've narrowed down the issue to specifically when there is an empty line on an input file.

Example of a successful file (each number is its own line):

10
8
7
5
0

Example of a failed file:

10
8
7
5
0

(The last line is empty space.)

The code is as follows.

//Attempting to build an array of up to twelve quiz scores.
int buildQuizArray(int quizArray[], string nameofile){
    ifstream infile;
    infile.open(nameofile);
    int quizzesread = 0;
    int input = 0;
    std::string line;
    int quiznum = 1;
    if (infile.fail()){
        cout <<"\n"<<nameofile << " did not open\n";
        exit(-1);
    }
    if (infile){
        while (quizzesread == 0 || (getline(infile, line) && quizzesread <12)){ //Currently reads one too many times if there's an empty space in a scoring file.
            infile >> input;
            quizArray[quiznum-1] = input;
            quizzesread++;
            quiznum++;
            test++;
        }
    }
    infile.close();
    return quizzesread;
}

I've tried implementing a check for if an empty line is detected using line.empty(), but all that does is cut off every single test after the first quiz entered into the array. I don't know what I'm missing.

12
  • Why are you doing both line-by-line reading getline(infile, line), and int-by-int extracting infile >> input;? Commented Mar 27 at 17:30
  • 3
    Be careful when mixing std::getline() with operator>> on the same istream: Why does std::getline() skip input after a formatted extraction? Why are you reading a line but ignoring its content? Commented Mar 27 at 17:43
  • 1
    The unanswered question here is what you want to happen if there is a blank line. Assuming the answer is that you just want to ignore it then the simple thing to do would be to forget about getline and just use >>, it will happily skip any line endings you have in your file. Commented Mar 27 at 17:48
  • 1
    Regarding the 'shoddy fix', yes it was. There is no reason that a properly coded loop will read the same last value twice. The correct loop is while (infile >> input) { ... }. The incorrect loop is something like while (!infile.eof()) { infile >> input; ... } I guess you had the latter loop originally. Commented Mar 27 at 17:50
  • 1
    Someone has been teaching you "C" (int quizArray[]) in C++ use : std::vector<int> to store the data, and if you want to pass it to a function call you can use std::span<int>. And then learn to use "range based for loops" Commented Mar 27 at 19:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.