简单的文件I / O程序C ++

时间:2014-09-04 05:05:39

标签: c++ c++11 file-io while-loop 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;
}

以上代码应该从文件“data.txt”中读取以下文本

“ifstream类型流的默认行为(打开文件时)允许用户 从文件中读取内容。如果文件模式是ios :: in,则只读取 在文本文件上执行,如果文件模式还包含ios :: binary ios :: in,读取以二进制模式执行。没有人物的转变 以二进制模式发生,而特定的转换发生在文本模式中。“

并创建一个文件out.txt,其中使用行号存储相同的文本(一行可以有75个字符或以'。'结尾 - 以较早者为准)。

每当我运行该程序时,它就会卡在控制台上 - 按下任何键都没有响应。

有人能告诉我这里发生了什么吗?

1 个答案:

答案 0 :(得分:4)

如果文件中任何一次尝试读取的时间超过74个字符,getline会为failbit设置fin,您永远不会到达文件的末尾。将您的代码更改为以下内容:

for (; fin; ++lc) {
  fin.getline(mline,75,'.');
  if (!fin.eof() && !fin.bad())
    fin.clear();
  fout<<lc<<". "<<mline<<"\n";
}

如果你到达文件的末尾或者流发生了灾难性的事情,这将打破你的循环。如果文件以句点结束,您还需要考虑处理执行的额外读取。

考虑切换到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";
}
相关问题