【问题标题】:eof() function not working c++ stuck with infinite loop [duplicate]eof()函数不起作用c ++陷入无限循环[重复]
【发布时间】:2012-10-09 02:30:18
【问题描述】:

可能重复:
Why is iostream::eof inside a loop condition considered wrong?

我遇到了 eof() 函数的问题。我的循环没有读取我正在读取的文件的末尾,因此给我留下了一个无限循环。任何帮助或见解将不胜感激。谢谢

 while (!file2.eof()) {

    getline (file2, title, ','); 
    getline (file2, authorf, ',');
    getline (file2, authorl, ',');
    getline (file2, isbn, ',');
    file2 >> pages;
    file2.ignore();
    file2 >> price;
    file2.ignore();
    getline(file2, subject, ',');
    file2 >> code;
    file1.ignore();
    file2 >> rentalp;
    file2.ignore(10, '\n');


    textbook b2(title, authorf, authorl, publisher, pages, isbn, price, code, subject, rentalp);
    b2.PrintTbook();
    TbookList[j] = b2; //initalizing the first element of the array to b2.
    newFile << "Title: " << TbookList[j].getTitle() << "\n" << "Price: " << TbookList[j].getPrice() << "\n\n";
    TbookList[j].PrintBook();
    j++;
    textbookCount++;
}

文本文件如下所示:

数据结构和算法分析实用入门,Clifford, Shaffer, 0-13-028446-7, 512, 90.00, Computer Science, E, 12.00, 2001 数据库系统基础, Ramez, AlMasri, 9-780805-317558, 955, 115.50, 计算机科学, E, 0.0, 2003

【问题讨论】:

  • 你能展示一个数据格式的样本吗?
  • 原因很简单:一次读取失败,file2.good() 为 false,后续所有读取尝试都会失败,但eof() 仍为 false,陷入死循环.
  • 试试这个:while(true) { /* get input */ if(!file2) break; /* use input data */ }
  • @SethCarnegie 我通常使用“file.good()”的原因之一,因为它检查所有条件而不仅仅是 1。
  • @JerryCoffin 我刚刚将文本文件添加到问题中。

标签: c++ infinite-loop eof


【解决方案1】:

首先,几乎所有while (!whatever.eof()) 形式的循环都被完全破坏了。

其次,我认为你有一个错字:

file1.ignore();

其余的代码是从file2 读取的,所以我猜file1 在这里只是一个错字(但如果你复制正确,它可能是问题的真正根源) .

您通常希望通过为您正在阅读的类型重载 operator&gt;&gt; 来执行此类操作:

std::istream &operator>>(std::istream &is, textbook &b2) {
    getline (is, title, ','); 
    getline (is, authorf, ',');
    getline (is, authorl, ',');
    getline (is, isbn, ',');
    is>> pages;
    is.ignore();
    is>> price;
    is.ignore();
    getline(is, subject, ',');
    is>> code;
    is.ignore();
    is>> rentalp;
    is.ignore(10, '\n');
    return is;
}

然后您可以读取一堆对象,例如:

std::vector<textbook> books;

textbook temp;

while (file2>>temp) {
    books.push_back(temp);
    temp.printbook();
    // ...
}

【讨论】:

  • 你的错字是无限循环的原因谢谢。我很想使用这种读取对象的替代方式,但我对此很陌生,而且还不是矢量的熟悉者,但是我会在上面做一些阅读
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2021-12-17
相关资源
最近更新 更多