ifstream's tellg() is unreliable

Jul 19, 2011 at 12:08pm
Hello, I have a text file (test.txt), the contents of which are
a

b
c
d
e


The program looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream a("test.txt");
    string x;
    a >> x;
    cout << x << endl;
    a >> x;
    cout << x << endl;
    a.seekg(a.tellg()); // Problem lies here.
    a >> x;
    cout << x << endl;
    a >> x;
    cout << x << endl;
    return 0;
}

If the a.seekg(a.tellg()) is present, the output is
a
b
d
e


However, if I get rid of it, the output is
a
b
c
d


Is there a more reliable way to use tellg and seekg, or am I using the wrong methods? If I save the tellg value to a variable and later use it in seekg to come back, it also doesn't go to the correct position.
Jul 19, 2011 at 12:18pm
You need to open it as binary http://www.cplusplus.com/reference/iostream/ifstream/open/

otherwise line endings are automatically converted (Win \r\n -> \n)
Jul 19, 2011 at 12:26pm
Thank you.
Topic archived. No new replies allowed.