从文件中读取时程序不会终止
Program does not terminate when reading from a file
看到代码中的大量文件操作,我有点尴尬。但好的旧freopen()
在这个特定的代码段-中让我失败了
int main()
{
ifstream fin;
int next=0;
fin.open("In.txt");
if(fin.is_open())
{
while(!fin.eof())
{
cout<<next;
next++;
}
}
else cout<<"Unable to open file"<<endl;
return 0;
}
我包含的标题是iostream、fstream和cstdio。这将进入一个无限循环。
我的问题是,我作为输入提供的文件肯定有结尾。但是为什么程序不终止呢?提前谢谢。
您几乎不应该使用eof()
作为文件读取循环的退出条件。尝试
std::string line;
if(fin.is_open())
{
while(getline(fin, line))
{
cout<<line;
}
}
如果你解释next
实际上应该做什么,我可以试着告诉你如何做,尽管我个人通常读取不需要任何控制整数的getline
或operator>>
文件。
您正在打开一个文件,但实际上并没有从中读取。每次检查是否已到达文件末尾时,流都在同一位置。
所以把它改成这样:
string word;
while(!file.eof()) {
file >> word;
cout << next;
next++;
}
相关文章:
- 堆栈粉碎终止程序
- 为什么我的显示功能会终止程序?
- 调用 raise(signal) 会终止 c++ 程序
- 使用终止程序的指针在数组中输入字符串
- C++ Argv[1] 终止程序,返回值 9009
- protobuf "oneof" sub-protobuf 对象指针终止程序
- 有没有办法避免在发生堆栈粉碎时终止程序
- c++ 终止程序的内存泄漏何时重要?
- C :CTRL D终止程序(Ubuntu)
- 用信号25终止程序,超过文件尺寸限制;为什么
- 是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式
- 正确关闭应用程序:终止程序的替代方案
- 提升线程终止程序
- Shell脚本终止程序,但导致无法写入输出文件
- 访问引用变量会终止程序
- 需要使用"enter"密钥终止程序
- C++按Enter键终止程序
- std::向量使用const_iterator终止程序
- Unicode导致关闭消息框终止程序
- 当我在函数中调用一个函数时,它会跳过代码并终止程序