问题
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