eof()函数不工作c ++与无限循环 [英] eof() function not working c++ stuck with infinite loop
问题描述
im对eof()函数有问题。我的循环不是读取文件的结尾,因此留下了一个无限循环。任何帮助或见解将非常感激。感谢
im having a problem with the eof() function. my loop is not reading the end of the file that im reading from thus leaving me with an infinite loop. Any help or insight would be greatly appreciated. thanks
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,Computer Science,E,0.0,2003
A Practical Introduction to Data Structures and Algorithim Analysis, Clifford, Shaffer, 0-13-028446-7, 512, 90.00, Computer Science, E, 12.00, 2001 Fundamentals of Database Systems, Ramez, AlMasri, 9-780805-317558, 955, 115.50, Computer Science, E, 0.0, 2003
推荐答案
几乎任何形式的循环 while(!whatever.eof())
完全折断。
First of all, almost any loop of the form while (!whatever.eof())
is completely broken.
有我的假设是一个错字:
Second, you have what I'm going to assume is a typo:
file1.ignore();
其余的代码是从 file2
,所以我想猜测 file1
只是一个拼写错误(但如果你正确地复制它,它可能是一个问题的真正的来源)。
The rest of the code is reading from file2
, so I'm going to guess file1
is just a typo here (but if you've copied it correctly, it could be the real source of a problem).
你通常希望通过重载 operator>>
/ p>
You usually want to do things like this by overloading operator>>
for the type you're reading:
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;
}
然后你可以读入一堆对象:
Then you can read in a bunch of objects something like:
std::vector<textbook> books;
textbook temp;
while (file2>>temp) {
books.push_back(temp);
temp.printbook();
// ...
}
这篇关于eof()函数不工作c ++与无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!