seekg() not working as expected

I have a small program, that is meant to copy a small phrase from a file, but it appears that I am either misinformed as to how seekg() works, or there is a problem in my code preventing the function from working as expected.

The text file contains:
//Intro
previouslyNoted=false


The code is meant to extract the word "false"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
std::fstream stats("text.txt", std::ios::out | std::ios::in);
//String that will hold the contents of the file
std::string statsStr = "";
//Integer to hold the index of the phrase we want to extract
int index = 0;

//COPY CONTENTS OF FILE TO STRING
while (!stats.eof())
{
     static std::string tempString;
     stats >> tempString;
     statsStr += tempString + " ";
}

//FIND AND COPY PHRASE
index = statsStr.find("previouslyNoted=");     //index is equal to 8
//Place the get pointer where "false" is expected to be
stats.seekg(index + strlen("previouslyNoted="));     //get pointer is placed at 24th index
//Copy phrase
stats >> previouslyNotedStr;

//Output phrase
std::cout << previouslyNotedStr << std::endl;


But for whatever reason, the program outputs:
=false


What I expected to happen:
I believe that I placed the get pointer at the 24th index of the file, which is where the phrase "false" begins. Then the program would've inputted from that index onward until a space character would have been met, or the end of the file would have been met.

What actually happened:
For whatever reason, the get pointer started an index before expected. And I'm not sure as to why. An explanation as to what is going wrong/what I'm doing wrong would be much appreciated.


Also, I do understand that I could simply make previouslyNotedStr a substring of statsStr, starting from where I wish, and I've already tried that with success. I'm really just experimenting here.
Your code shouldn't work at all.

After the loop at line 8, stats will be in an eof state. This is not a good state ( literally http://www.cplusplus.com/reference/istream/istream/seekg/ ), and seekg doesn't work unless the state is good.

I was able to get your code working as expected by adding stats.clear() at line 14.

C++11 made it possible to seek away from EOF.

I think the problem is the use of seekg on a file opened in text mode: in text mode, the only arguments for which seekg is well-defined are zero and a value obtained from a previous call to tellg.

(in particular, I would guess the OS is Windows, and your 24th byte position is actually your 23rd character, because one of the characters, the '\n', is two bytes in the file)

Unrelated, but "while (!stats.eof())" is almost always wrong: you're running off the end of file and then appending an extra lonely space to the result string. Use "while(stats >> tempString)"
Topic archived. No new replies allowed.