Mon*_*onk 2 c++ file-io while-loop c++11 codelite
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该从文件“data.txt”中读取以下文本
“ ifstream 类型流的默认行为(在打开文件时)允许用户从文件中读取内容。如果文件模式是 ios::in 则仅对文本文件执行读取,如果文件模式还包括 ios:: binary 和 ios::in 然后,读取是在二进制模式下执行的。在二进制模式下不会发生字符转换,而在文本模式下会发生特定的转换。”
并创建一个文件 out.txt ,其中使用行号存储相同的文本(一行可以有 75 个字符或以 '.' 结尾 - 以较早者为准)。
每当我运行该程序时,它就会卡在控制台上 - 按下任何键都不会响应。
有人能告诉我这里发生了什么吗?
如果文件中任何一次尝试读取的长度超过 74 个字符,getline则会设置failbitfor fin,并且您将永远不会到达文件的末尾。将您的代码更改为以下内容:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
Run Code Online (Sandbox Code Playgroud)
如果您到达文件末尾或流发生灾难性事件,这将中断您的循环。您还需要考虑处理在文件以句点结尾时执行的额外读取。
考虑切换到std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5529 次 |
| 最近记录: |