当在具有读入int数组的文件中使用c ++ getline()循环时? [英] c++ getline() looping when used in file with a read in int array?

查看:55
本文介绍了当在具有读入int数组的文件中使用c ++ getline()循环时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,前几天我发布的信息不够多,一旦添加了所要求的信息,就再也没有答案,所以我无法使循环正常工作,所以我的问题是,我正在从包含大文件的文件中进行读取每行上的字符串文本,然后在下一行上有整数,需要将字符串读入questionArrays(),并将整数读入answersArrays.

So I posted this the other day with not enough information and never got an answer once I added the information asked, so I can't get the loop to work so my question is, I am reading from a file that has large text of strings on each line, it then has ints on the next line the strings need to be read into questionArrays() and the ints into answersArrays.

当前循环仅循环一次,然后循环,因为它在下一个getline()上的文件中没有得到进一步的处理了,我确实在没有读取ints部分的情况下进行了此工作,所以我认为这是中断它的原因.当前,文件也按字符串,整数,字符串,整数等顺序排序,如果有一种将它们拆分成小写的方式,那也是可以接受的答案.

Currently the loop simply goes round once and then just loops as it doesn't get any further in the file on the next getline() I did have this working without the reading of ints part so I assume this is what breaks it. The file is also currently ordered in order of string then int then string then int and so on, if there is a way of splitting these up to read in that would also be an accepted answer.

ifstream questionFile;
int i = 0;
switch (x){
case 1:
    questionFile.open("Topic1 Questions.txt", ios::app);
    break;
case 2:
    questionFile.open("Topic2 Questions.txt", ios::app);
    break;
case 3:
    questionFile.open("Topic3 Questions.txt", ios::app);
    break;
case 4:
    questionFile.open("Topic4 Questions.txt", ios::app);
    break;
}
if (!questionFile)
{
    cout << "Cannot load file" << endl;
}
else
{
    if (questionFile.peek() != ifstream::traits_type::eof()) {
        while (!questionFile.eof())
        {
            getline(questionFile, questionsArray[i]);
            questionFile >> answersArray[i];
            i++;
        }
    }
    questionFile.close();
}

推荐答案

>> 将使用该数字,但不使用行的其余部分(包括行尾标记).因此,下一个 getline 将读取一个空行,而下一个>> 将失败,从而使流进入您不检查的不良状态.然后它将永远循环,不读取任何内容,并且永远不会到达文件末尾.

>> will consume the number, but not the remainder of the line (including the end-of-line marker). So the next getline will read an empty line, and the next >> will fail, putting the stream into a bad state that you don't check for. It will then loop forever, reading nothing and never reaching the end of the file.

您需要:

  • 忽略答案行的其余部分
  • 检查失败
  • 在读取后而不是之前检查文件结尾.

更好的循环结构可能看起来像

A better loop structure might look something like

while (getline(questionFile, questionsArray[i])) {
    if (questionFile >> answersArray[i]) {
        questionFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } else {
        throw std::runtime_error("Missing answer"); // or handle the error somehow
    }
    ++i;
}

这篇关于当在具有读入int数组的文件中使用c ++ getline()循环时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆