reading a file

hey guys ..
I was trying to read a file using the end of file (eof) statement ..
however when the file is finished it didn't stop !
it is reading the last line one more time and saving its data ..
any help ?

this is my code :
1
2
3
4
5
6
7
8
9
10
11
12
while(!file1.eof() )
	{
	
		file1 >> s;
		H.word = s ;
		file1 >> s1;
		H.pos = s1 ;
                file1 >> s2 ;
		H.pseudo_root = s2 ;
		verb.push_back(H);
		H.clear()
         }


my purpose is to take the input from a file and to store it in a vector using a predefined class .. but like i said it is reading the last line twice ..

help me ..
Well, it doesn't actually read the last line twice. Rather, your code reads s, s1 and s2 from the file, but doesn't check whether or not the input operation succeeded. The push_back() and other statements are executed even if the input has failed. That's the first problem.

After that, execution returns to the top of the loop and tests the eof() condition. That's the second problem. When an input operation succeeds, it doesn't necessarily set the eof flag. Why not? Well, there may be some white space such as a newline character after the last data item.

Generally the use of eof() is not the best way to do things. Instead, just test that the input operation was successful before proceeding to use the resulting values.
1
2
3
4
5
6
7
8
while ( (file1 >> s) && (file1 >> s1) && (file1 >> s2) )
{
    H.word = s;
    H.pos  = s1;
    H.pseudo_root = s2;
    verb.push_back(H);
    H.clear()
}


Or read all three values in the same statement, like this:
1
2
3
4
5
6
7
8
while ( file1 >> s >> s1 >> s2 )
{
    H.word = s;
    H.pos  = s1;
    H.pseudo_root = s2;
    verb.push_back(H);
    H.clear()
}
Last edited on
so the test of the input success can be used to expressed the end of file ?
could you explain why ?
It doesn't directly test for the end of file. I don't know the type of your variables s, s1 and s2, so the behaviour might differ for say int or string types. But basically, if you do this:

1
2
string word;
file1 >> word;

the >> extraction operator will first read and ignore any leading whitespace. Then, if we assume it finds a letter such as 'A', it will add that, and any non-whitespace characters to the variable word until either
1. a whitespace character is found, in which case it is left in the file buffer, or
2. the end of file is reached.

After this operation, if a value was successfully read into the variable, the fail flag will be off. If it was not successful, the fail flag is set on. As for the eof flag, well it may or may not be set, depending upon whether there was any trailing whitespace after the data item.

We don't actually care whether the end-of-file flag was set or not. We are only interested in whether or not the input operation was successful.
Last edited on
oh ok i can see now your point .. thanks alot for your time :)
Topic archived. No new replies allowed.