i wrote the following code….
#include< iostream>
#include< fstream>
using namespace std;
int main()
{
ifstream in("text1.dat",ios::in);
enum choice{zero=1, credit, debit, exit};
choice your;
int balance;
char name[50];
int option;
while(cin>>option)
{
if(option==exit)
break;
switch(option)
{case zero:
while(!in.eof())
{in>>balance>>name;
if(balance==0)
cout<<balance<<" "<<name<<endl;
cout<<in.tellg()<<endl;
}
in.clear();
in.seekg(0);
break;}
// likewise there are cases for debit and credit
system("pause");
return 0;
}
In text1.dat the entry was:
10 avinash
-57 derek
0 fatima
-98 gorn
20 aditya
and the output was:
1 //i input this
16
27
0 fatima
36
45
55
-1 //(a)
3 //i input this
10 avinash
16
27
36
45
20 aditya
55
20 aditya //(b)
-1
my questions are:
- the output marked ‘a’ is -1…what does -1 mean as an output of tellg()?
- the output marked ‘b’ is repeated…why so?
You are observing the same behavior as many other novice C++ programmers. Read for example this question.
What happens is that
in.eof()is set totrueafter you’ve tried to read something frominand the operation failed because there was no more data. When a read operation fails due to end-of-file, it sets both,eofbitandfailbit. When a stream is in fail state, thetellgfunction is documented to return-1.To solve the problem, test for
eofafter you perform a read operation and before you do anything else. Even better, check that the operation just ‘failed’, since you don’t want to distinguish between an end-of-file and an incorrect input (e.g. if a string is fed instead of an number for the balance, your code enters an infinite loop):The
!incondition checks that eitherfailbitorbadbitare set. You can simplify this by rewriting as: