在C++中读取文件时应用程序冻结

Application freezes while reading from file in C++

本文关键字:应用程序 冻结 文件 读取 C++      更新时间:2023-10-16

所以这是我的文本文件:

计算机科学4.3458485341.伊万·伊万诺夫Georgi GeorgievPlamen Angelov======奥利里伦敦第五大道44384208434*****************生物学2.589346730伊万诺夫尼古拉·斯塔马托夫杰克·约翰逊======头部优先曼彻斯特斯坦利街4号449348344

这是我从文件中读取的函数:

void ApprovedBook::read_from_file() {
fstream file;
string heading; int edition; long ISBN = 0L; bool isApproved = 0; // temp values   for each book 
string name; string address; long telephone = 0L; // temp values for manufacturer of the book
vector<string> authors; // temp vector for authors of the book  
string line;
file.open("books.txt", ios::in | ios::app);
while (file.good()) {
for (int i=1; i<=NUM_ITEMS; i++) { 
getline(file, line);
switch (i) {
case 1: 
heading = line; break;
case 2:
edition = atoi(line.c_str()); break;
case 3:
ISBN = atol(line.c_str()); break;
case 4:
isApproved = (bool) atoi(line.c_str()); break;
}
}
getline(file, line);
while (line != "======") {
authors.push_back(line);
getline(file,line);
}
int i = 1;
getline(file, line);
while (line != "*****************") {
switch (i) {
case 1: 
name = line; break;
case 2:
address = line; break;
case 3: 
telephone = atol(line.c_str()); break;
}
getline(file, line);
i++;
}
Manufacturer m(name, address, telephone);
ApprovedBook a(heading, authors, edition, ISBN, m, isApproved);
cout << a << endl;
authors.clear();
}
file.close();
}

因此,我用***行分离构建"ApprovedBook"对象所需的信息。需要"====="和星星之间的线来构造"Manufacturer"对象,该对象也是ApprovedBook的属性。所以我读取第一条信息并输出具有<lt;(我已经为类预定义了运算符)。但在那之后,应用程序冻结,似乎无法读取恒星下方的下一条信息。这有什么问题?文件.good()的条件是否足够,或者可能需要一些更高级的检查?

while (line != "*****************") {对于最后一条记录将始终为true,除非在输入文件末尾添加星号。

在我看来,你也需要这一行来检查你的文件:

while (file.good() && line != "*****************") {

我用while(line!=")替换了file.good,这对我来说很好。