-
random access
Hi there. I want to read from a text file witch contains five names.
The program must display the context of the file in reverse order. Now, everything works fine as long as the names are all on the same line, e.g. Tom Boby Sarah Elena George
but if the names are in separate lines like one name per line then it only desplayes the last name(txt file attached). How do i fix this?
Thanks for your help
Code:
ifstream fp;
int main()
{
char in_char;
fp.open("names.txt", ios::in);
if(!fp)
{
cout<<"**Error opening file**\n";
exit(0);
}
fp.seekg(-1l,ios::end);
while(fp.get(in_char))
{
fp.seekg(-2l,ios::cur);
cout<<in_char;
}
fp.close();
getch();
return 0;
}
-
My guess is that you are reaching the eof, and thus thyat flaqg is set. Therefore in your while(fp.get(in_char)) is returning false and therefore terminating after the first read. Do this:
[code]
while(fp.get(in_char))
{
fp.clear(); //reset the flag
fp.seekg(-2l,ios::cur);
cout<<in_char;
}
-
That doesn't seem to work. Also i think that the while loop doesnt return false after the first read because it desplays the last name.
i put a delay in the loop so i can see what it does and it shows one character at a time -haras (sarah(the last name in the txt file) in reverse) and then it goes to a new line, prints nothing and again the same thing a few more times.
Code:
while(fp.get(in_char))
{
fp.clear();
fp.seekg(-2l,ios::cur);
cout<<in_char;
delay(500);
}
-
Sorry about that, here I ran this one myself. It works:
Code:
fstream fp;
char in_char;
fp.open("names.txt", ios::in|ios::binary);
if(!fp)
{
cout<<"**Error opening file**\n";
cin.get();
exit(0);
}
fp.seekg(-1l,ios::end);
while(fp.get(in_char))
{
fp.seekg(-2l,ios::cur);
cout<<in_char;
}
-
:D Thanks traveller. Exselent !!!
Man don't know why but random access files gave me such a headache this last two days. I really blame the book am using.
BTW thanks also for sugesting a book yesterday , i'll definatly give it a try.:cool: