Why the double not in this while loop?

In some code I'm studying I found this double not.

Can it be replaced with just while(fin)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	...
        ifstream in(sourceFilename.c_str());
        ...

	try{
		stringstream fin;

		CommentOutStream(fin, in, "#");

		while(!!fin){
			string key;

			fin >> key;

			if(key=="") continue;
                        ...

		}
            }
         ...


CommentOutStream basically populates the stringstream from the ifstream.
Although while (!!fin) should be equivalent to while (fin)
there are other problems with this code.

At lines 13-15 there is this:
13
14
15
    fin >> key;

    if(key=="") continue;
however there is no check after line 13 to see whether or not the input was successful. For example when the end of the stream is reached it will fail.

A usual alternative is this:
1
2
3
4
5
    string key;
    while (fin >> key)
    {
        if (key=="") continue;
        ... etc.


Of course if you are not the author of the code then who knows...

Edit:
Actually, i see the difference now. In the original code, string key is defined inside the loop, that means it will be initialised as an empty string. When the input fails, the string will be empty. But if defined before the loop, then key could retain some previous value. However in my suggested version, the body of the loop will never be entered unless the input was successful, so there's no need to be concerned about the case where key == "", that code can now be omitted. So the code simplifies to
1
2
3
4
    string key;
    while (fin >> key)
    {
        ... etc.
Last edited on
Topic archived. No new replies allowed.