处理文件冻结程序
C++ Processing file freezes program
我正在编写一个小程序,它接受输入文件并处理文件中的数据。使用我当前的代码(见下文),当你输入一个有效的文件名时,它只是冻结命令行(下拉一行,只显示一个闪烁的_),我必须杀死程序才能退出。如果您输入一个无效的文件名,If(!)文件将被调用并正常运行。真正奇怪的是,如果我在if语句上面放一个调试代码,如果文件名是正确的,它将不会被调用。希望你能帮助,如果你需要更多的信息,让我知道!
这是我当前的代码:
using namespace std;
#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include "Student.h"
int main(){
string filename, name;
char *inputfile;
ifstream file;
vector<Student> students;
const int SIZE = 200;
char buffer [SIZE];
int regno, i;
cout << "Enter file name: ";
cin >> filename;
inputfile = const_cast<char*> (filename.c_str());
file.open(inputfile);
if (!file){
cout << "Failed to open " << filename << endl;
exit(1);
}
while (!file.eof()){
file.getline(buffer, SIZE);
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
cout << regno;
}
file.close();
}
你的问题是你在循环中从不增加i。
:
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
你进入无限循环,因为i总是保持0
为什么要做const_cast?也可以使用const char *来打开。所以你可以这样写:
cin >> filename;
file.open(filename.c_str());
代码仍然可以工作
关于使用getline()
和eof()
的代码中还有另一个问题。逐行读取文件的惯用方法如下:
std::string line;
while(getline(in, line)) {
// handle line here
}
in
指的是std::ifstream或std::cin等输入流。关键是读取一行可能会失败(例如,由于EOF),您可以在上面的循环中检查。您的版本只检查之前是否遇到了EOF,而不检查随后的getline()
调用是否实际产生了任何数据。
相关文章:
- WIN32:C++,为什么在WM_CLOSE上调用Messagebox函数程序正在冻结
- 程序在对mouse_event的 Windows API 调用中冻结
- C++(SFML?激活某些内容x秒钟,而不会冻结整个程序
- 并行 Python-C++ 程序冻结(内存?
- QT应用程序冻结
- 如何提高四叉树代码的性能以防止程序冻结
- 使用 cin 读取大型输入时程序冻结
- 在C++中读取文件时应用程序冻结
- 由于函数阻止程序执行而导致程序冻结
- 调用删除会导致程序冻结C++
- SRAND 导致我的程序冻结
- 视觉C++程序冻结深奥
- C++程序冻结和UI变为全白
- 程序冻结/循环
- 函数调用会导致C++程序冻结,除非在调试器中逐步执行
- 为什么这个子网类应用程序冻结了
- 当我调用一个函数时,c++列表程序冻结
- Win32 API:打开对话框窗口后应用程序冻结
- 当添加一个用于监听网络的新线程时,应用程序冻结
- 更新CListCtrl时MFC应用程序冻结