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.