可能重复: 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,计算机科学,E,12.00,2001年数据库系统的基本原理,Ramez,AlMasri,9-780805-317558,955,115.50,计算机科学,E,0.0,2003年
发布于 2012-10-09 02:44:50
首先,几乎任何形式的while (!whatever.eof())循环都是完全中断的。
第二,我要假设的是一个错误:
file1.ignore();剩下的代码是从file2中读取的,所以我猜file1只是这里的一个错误(但是如果您正确地复制了它,它可能是问题的真正来源)。
您通常希望通过重载您正在阅读的类型的operator>>来做这样的事情:
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();
// ...
}https://stackoverflow.com/questions/12792079
复制相似问题