首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不工作c++的eof()函数在无限循环中卡住

不工作c++的eof()函数在无限循环中卡住
EN

Stack Overflow用户
提问于 2012-10-09 02:30:18
回答 1查看 2.3K关注 0票数 1

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

我对eof()函数有问题。我的循环不是读取我读取的文件的末尾,因此给我留下了一个无限循环。任何帮助或洞察力都将不胜感激。谢谢

代码语言:javascript
复制
 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年

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-09 02:44:50

首先,几乎任何形式的while (!whatever.eof())循环都是完全中断的。

第二,我要假设的是一个错误:

代码语言:javascript
复制
file1.ignore();

剩下的代码是从file2中读取的,所以我猜file1只是这里的一个错误(但是如果您正确地复制了它,它可能是问题的真正来源)。

您通常希望通过重载您正在阅读的类型的operator>>来做这样的事情:

代码语言:javascript
复制
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;
}

然后,您可以在一堆对象中读到这样的内容:

代码语言:javascript
复制
std::vector<textbook> books;

textbook temp;

while (file2>>temp) {
    books.push_back(temp);
    temp.printbook();
    // ...
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12792079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档