read from file only from one specific line to another C++

寵の児 提交于 2019-12-08 14:05:00

问题


Is there any way how to read data from file from line to another line ?

For example :

In file are these lines:

Line1: empty line

Line2: empty line

Line3: robert wa

Line4: frank le

Line5: silvia op

Line6: empty line

Line7: empty line

Line8: andy sf . .

And I need to only read everything from Line3 to Line6

So output will be : robert wa frank le silvia op

And my file have 300 lines that I want print.

Do you have any idea how to do it, or can you paste me some pseudocode

Thanks


回答1:


This should do the trick:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

    int main()
    {
        string line;
        ifstream infile;
        infile.open("putyourinputfilehere.txt");
        while(getline(infile, line))
        {
            if(line != "")
            {
                cout << line << endl;
            }

        }
        infile.close();
        return 0;
    }



回答2:


Use std::getline to read one line from an input stream (e.g. an ifstream). You can then print only those that you're interested.




回答3:


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

 int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      if(line.empty())
      {
        cout<<"Empty line";
      }
      else
      {
        //do some work
      }
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}


来源:https://stackoverflow.com/questions/23209935/read-from-file-only-from-one-specific-line-to-another-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!