caramel1995 caramel1995 - 3 months ago 12
C++ Question

ifstream tellg() not returning the correct position

The code is as follow :

The Code:



#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
int id;
char name[50];
ifstream myfile("savingaccount.txt"); //open the file
myfile >> id;
cout << myfile.tellg(); //return 16? but not 7 or 8
cout << id ;

return 0;
}


The File Content:




1800567
Ho Rui Jang
21
Female
Malaysian
012-4998192
20 , Lorong 13 , Taman Patani Janam
Melaka
Sungai Dulong


The Problem :



1.) I expect the
tellg()
to either return
7
or
8
since the first line
1800567
which is 7 digits so the stream pointer should be placed after this number and before the string
"Ho Rui Jang"
, but
tellg()
returns
16
. Why is it so?

Answer

This seems more like a compiler bug (probably gcc)

With the following Code:-

#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    cout << myfile.tellg()<<endl;
    myfile >> id;
    streamoff pos=myfile.tellg();
    cout <<"pos= "<<pos<<'\n';
    cout <<"id= " << id<<'\n' ;
    return 0;
}

Following is the output:-

Bug

In the image inpstr.exe was generated from Visual studio's cl while inp.exe from g++(gcc version 4.6.1 (tdm-1))

Comments