【发布时间】: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