在C++中读取文件时应用程序冻结
Application freezes while reading from file in C++
所以这是我的文本文件:
计算机科学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,这对我来说很好。
相关文章:
- 试图在visual studio上用C++创建一个桌面应用程序
- QT应用程序冻结
- QT应用程序接口冻结
- 如何在不冻结线程/应用程序的情况下减慢方法执行速度
- 在线程中复制文件以防止冻结应用程序
- 在C++中读取文件时应用程序冻结
- 监视C++OpenFrameworks应用程序是否冻结或内存泄漏,然后强制退出并重新启动
- 在这个基于对话框的应用程序中,GUI会在几秒钟后冻结
- 故意在 VB.NET 中冻结应用程序
- 如何在不冻结应用程序 1 的情况下从另一个应用程序 1 执行应用程序 2
- 在 android 上向 JNI 类添加私有字段会冻结应用程序
- Qt 应用程序在从 <QUrl>NetworkAccessManager->get() 回调访问 QList<QLlnkedList* >时冻结
- 为什么这个子网类应用程序冻结了
- Qt事件后,长例程冻结了我的应用程序一段时间
- Win32 API:打开对话框窗口后应用程序冻结
- c++ linux时间冻结应用程序
- wxWidgets应用程序在尝试启动新对话框时冻结
- 当添加一个用于监听网络的新线程时,应用程序冻结
- 更新CListCtrl时MFC应用程序冻结
- Linux应用程序在boost::thread::join时冻结