After I read a line from a file using ifstream, is there a way to bring the stream back to the beginning of the line I just read, conditionally?
using namespace std;
//Some code here
ifstream ifs(filename);
string line;
while(ifs >> line)
{
//Some code here related to the line I just read
if(someCondition == true)
{
//Go back to the beginning of the line just read
}
//More code here
}
So if someCondition is true, the next line read during the next while-loop iteration will be the same line I just read right now. Otherwise, the next while-loop iteration will use the following line in the file. If you need further clarification, please don't hesitate to ask. Thanks in advance!
UPDATE #1
So I tried the following:
while(ifs >> line)
{
//Some code here related to the line I just read
int place = ifs.tellg();
if(someCondition == true)
{
//Go back to the beginning of the line just read
ifs.seekg(place);
}
//More code here
}
But it doesn't read the same line again when the condition is true. Is an integer an acceptable type here?
UPDATE #2: The Solution
There was an error in my logic. Here is the corrected version that works as I want it to for any of those that are curious:
int place = 0;
while(ifs >> line)
{
//Some code here related to the line I just read
if(someCondition == true)
{
//Go back to the beginning of the line just read
ifs.seekg(place);
}
place = ifs.tellg();
//More code here
}
The call to tellg() was moved to the end because you need to seek to the beginning of the previously read line. The first time around I called tellg() and then called seekg() before the stream even changed, which is why it seemed like nothing changed (because it really hadn't). Thank you all for your contributions.
There is no direct way to say "get back to the start of the last line". However, you can get back to a position you kept by using std::istream::tellg()
. That is, before reading a line you'd use tellg()
and then seekg()
to get back to the position.
However, calling the seek functions frequently is fairly expensive, i.e., I would look at removing the requirement to read lines again.