c++ - Array copies one too many values if there is an empty line in the input file? - Stack Overflow

Working on an assignment for my coding class which involves the function below, which is supposed to re

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744076749a4554541.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信