2
#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;
}

The above code is supposed to read from the file "data.txt" the following text

"The default behaviour of ifstream type stream (upon opening files ) allows users to read contents from the file. if the file mode is ios::in only then reading is performed on a text file and if the file mode also includes ios::binary along with ios::in then, reading is performed in binary mode. No transformation of characters takes place in binary mode whereas specific transformations take place in text mode."

and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).

Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.

Can someone tell me what's going on in here ?

4

1 回答 1

5

如果文件中任何一个尝试读取的长度超过 74 个字符,getline将设置failbitfor 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";
}
于 2014-09-04T05:21:39.000 回答