kindly try to learn scope of a variable in c/c++, this will make it clear, i suggest u dont proceed with ur programs before learning the scope of variables.
Since when does a variable go out of scope when it enters a while loop? That doesn't seem logical at all. If this is the case I'll keep it in mind, but I'd appreciate another opinion. But, perhaps that's for a different place, I'll assume it's some strange memory buggery and move on with life. Problem solved.
You define the second line inside the while-loop, so it only exists INSIDE the body of the while-loop. The check of the value of line is not part of the body of the while loop. So it has to take the first line variable.
Your second solution is still way too complicated, the easiest way to solve your problem is to just delete the second line variable. Then the outer line variable (the first one) functions as a proper variable for the check at the beginning of iteration. I see no reason why you need the second line variable at all.
Like, in a while loop you got a variable which gets assigned a new value in each iteration, and it's that variable you test. And the variable must exist before the check gets performed for the first time. So you can't declare it inside the body of the while-loop.
@DOCFail, the line variable doesnt go out of scope when it enters the while loop, the local variable with same name takes higher priority, whenever u use variable line in the loop, the local variable declared in the loop will be considered.
I'll assume it's some strange memory buggery and move on with life. Problem solved.
Don't give up that early.
remove line 8 from the code of your original post.
the second problem is that you open the file from within the loop. You read the first line of the file and close it. You will never see the second line of the file.
the while on line 4 will see line on line 3 while the if on line 12 will see line on line 8.
I'll assume it's some strange memory buggery and move on with life. Problem solved.
No. No, it isn't. And if you do that, you'll have failed to understand something very important about variables in C++ (and C).
The variable line that you declare on line 9 is a different variable from the one you declare on line 3. Within the while loop, the one on line 9 hides the one on line 3, so in your original code, when you do the comparison if(line == "Hello"), you're checking the contents of the local variable.
The way you've changed it now, you're not setting the local variable (declared on line 9) at all. Therefore the if(line == "Hello") test will never be true, so you might as well delete those things.