While loop
Apr 11, 2010 at 3:19am UTC
Hi Programmers,
I'm writing a program to read text file and display it on the screen but it just works for the first time and if I tried again it doesn't display anything!
This is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
ofstream outDictFile( "Dict.dat" , ios::app );
ifstream inDictFile( "Dict.dat" , ios::in );
int main()
{
char cont;
string line;
do
{
while ( getline( inDictFile, line ))
cout << " " << line << endl;
cout << "\nPress \"y\" to continue or any key to exit... " ; cin >> cont;
} while (cont == 'Y' || cont == 'y' );
}
What's going wrong?
Apr 11, 2010 at 3:48am UTC
this might work after do.
1 2
inDictFile.clear(); // clear the eof
inDictFile.seekg(0); // set get pointer to the beginning
Apr 11, 2010 at 4:01am UTC
Yeaaah it works :), can you explain further what did these two lines do with my code? I mean what happen before and after adding them.
Apr 11, 2010 at 5:44pm UTC
http://www.cplusplus.com/doc/tutorial/files/
1. once you hit the end of file(eof) it trip a flag.
this flag must be reset.
.clear()
2. your get pointer was at the end.
the get pointer is where it start reading data.
File
> this is the pointer for my example
each dot stands for a number or character.
. . .
. . . . . .
. . . .
. . . . . . .
. .>
.seekg(0)
>. . .
. . . . . .
. . . .
. . . . . . .
. .
Topic archived. No new replies allowed.