Get a specific line from ifstream
Hiya
I'm coding a parser for text files, and need some help figuring out why the stl is playing tricks on me.
What I want:
The parser will go through the text, line by line, and do some stuff.
When a certain line is reached, I want to store its position so I can return to it later, and continue to parse from that position onwards.
It's easy to do it by storing all the lines in a string vector, but I don't want to waste memory to hold the entire text file.
So I read about tellg and seekg, and thought I will be good to go with the following code:
the function:
Code:
void Parse(std::string Filename) {
std::ifstream f;
// Open the file for parsing.
f.open(Filename.c_str(), std::ifstream::in);
if (f.is_open()) {
std::string line;
std::streampos line_three = std::ios::beg;
// Read some lines from the file.
while (f.good()) {
std::streampos pos = f.tellg();
std::getline(f, line);
// Store the position of the line "hello world".
if (line == "hello world") {
line_three = pos;
}
}
f.clear();
f.seekg(line_three, std::ios::beg);
//f.seekg(-2, std::ios::cur);
std::getline(f, line);
std::cout << "Line#3: " << line << std::endl;
f.close();
}
return;
}
text.txt:
Code:
some text
some more text...
hello world
finish!
But instead of printing the third line, my output is:
I must be doing something stupid, but I couldn't find out what exactly.
Thanks