Reputation: 37
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
system("cls");
fstream obj;
obj.open("today.txt",ios::in);
char ch;
while (obj)
{
cout<<endl<<"file pointer at :"<<obj.tellg();
obj>>ch;
}
cout<<endl<<obj.tellg();
return 0;
}
output :
file pointer at :0
file pointer at :1
file pointer at :2
file pointer at :3
file pointer at :4
file pointer at :5
file pointer at :7
file pointer at :8
file pointer at :9
file pointer at :10
file pointer at :11
-1
Upvotes: 1
Views: 625
Reputation: 188
tellg
is returning -1 because it has encountered an error while reading the obj!! As while
loop exits once the file has reached its end (no more data to read) and so obj is null and hence tellg
return -1.
Refer to this site for more information- http://www.cplusplus.com/reference/istream/istream/tellg/
Upvotes: 0
Reputation: 25980
From the docs:
Return value:
The current position in the stream. If either the stream buffer associated to the stream does not support the operation, or if it fails, the function returns -1.
So tellg
is "failing". A common reason is if you hit the end of the stream (a file here). This makes sense since you iterate until the end of the stream just before.
Upvotes: 2