第十四四周项目二 改写文件并另存

来源:互联网 发布:怎样网络上发布小说 编辑:程序博客网 时间:2024/05/22 23:31

问题及代码

/*  ALL rights reserved.                          *文件名称: 初学对象14                      作者:李长鸿                       *完成时间:2015.6.17                *问题描述: 文件改写并另存*/    #include <iostream>#include <cstdlib>#include <fstream>using namespace std;int main(){    fstream outfile,infile;    infile.open("abc.txt",ios::in); // (1)    if(!infile) {        cout<<"Can¡¯t open the file."<<endl;        abort();    }    outfile.open("newabc.txt",ios::out);//(2)    if(!outfile) {        cout<<"Can¡¯t open the file."<<endl;        abort();    }    char buf[500];    int i=1;    while(!infile.eof()) // (3)    {        infile.getline(buf,500); // (4)        outfile<<i++<<": "<<buf<<endl; //(5)    }    infile.close();    outfile.close();    return 0;}


总结:原先错误原因见老师的:

           当abc.txt文件中存在长于80个字符的行时,程序会陷入死循环。通过跟踪发现,从当遇到这个“超长”的行时,infile.getline(buf, 80)先读出79个字符,以\0结束,之后再读,buf[0]总是\0,同时!infile.eof()为假,所以进入死循环。怀疑这其中该是这种“截断”式读取超长行带来的副作用。参看《getline的获取ifstream的数据》,其中给出了解释与对策。
显然,当初的这个程序并未考虑超长行,而是默认每一行都不会达80个字符而设计的。注意:如果某一行就这样被“截断”了,并不意味着这就是一行,直到找到换行符,才能说明这是一行的结束,行数i++才能执行,这个程序的改进又可以进行了。

0 0
原创粉丝点击