最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论