1
这是一个应该从文本文件中读取书籍清单的程序(对于每本书,文本文件的每一行都按照正确的顺序包含不同的字段)。由于某种原因,例行程序无限期地继续下去。 “eof”错误陷阱似乎无法捕捉文件的结尾。有人可以给我一个想法是什么错?请记住我是C++世界的真正新手,但不是编程的新手。将文本文件中的数据读入C++结构
首先,我已经包含了正确的头文件书
// structure definition
struct Book
{ string isbn;
string title;
string author;
string publisher;
int quantity;
float price; };
的结构定义。下面是似乎没有工作的例程。我把一些cout < <“放到第一行”endl;代码来查看例程的进度,并且它只是重复从文本文件中提取数据。该文本文件中只有6本书,所以它应该快速读取文本文件。
非常感谢您的帮助!
void readInventory(string fileName, vector<Book>& inventory)
{
ifstream instream;
// tries to open the file
instream.open(fileName);
// checkes if the file is open
if (instream)
{
// string line;
// reads through the file line by line
while (!instream.eof())
{
Book newBook;
// read book from text file
instream >> newBook.isbn;
instream >> newBook.title;
instream >> newBook.author;
instream >> newBook.publisher;
instream >> newBook.quantity;
instream >> newBook.price;
// add this book to inventory
inventory.push_back(newBook);
}
instream.close();
showMessage(to_string(inventory.size()) + " books were successfully added to inventory");
}
// if failed to open the file
else
showMessage("Cannot open the file. Make sure the file name is correct");
}
问题1.'instream.eof()' - 见https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong。 PS:在开始时删除人生故事 - 不是暗指 –
新文件中的结构文件中的所有数据即isbn,标题都是同一行吗? –
检查这个问题以及https://stackoverflow.com/questions/6512173/ifstream-not-reading-eof-character –