Hi, I'm a beginner for C++. I want to use while function properly, but there is a tricky part.
I tried to read line character from file. So I made a Class. Anyway, I used do-while loop for reading my line, but I want to simplify my code. for example just using while. To tell the truth, at First, I tried to read line until it finishes, but if I wrote a code using while loop, I have a difficulty. It read line two times, so that I lost my every odd line..
Is there any other solution to read line properly by using while loop?
Or should I keep this code..?
1 2 3 4 5 6 7
while(SetPath.ReadLine() !=NULL)
{
line = SetPath.ReadLine();
if (line == NULL)
break;
string strline(line);
}
so That's why I wrote my code by using do-while loop instead of while loop.
1 2 3 4 5 6 7
do
{
line = SetPath.ReadLine();
if (line == NULL)
break;
string strline(line);
}while(line !=NULL);
I am going to show you something that should not be used in general as it can cause confusion, but it works well in this specific case. Please do not overuse what I will be showing you.
First of all, the reason this problem occurs is that you are reading the line twice in the function, first to evaluate whether to continue or not, and secondly to store the line in the variable "line". By calling the function twice, you are skipping one of the lines, since you did not store the first call of the function.
Now for the part that should not be overused:
The nice thing about if and while statements is that you can set a variable to something and then immediately check the variable.
while ((line = SetPath.ReadLine()) != NULL) // first you set the variable, and then you evaluate the variable
A more compact way of doing this is the following:
while (line = SetPath.ReadLine())
As anything but NULL or 0 is equal to true, and while loops evaluate to check true or false, you do not need the != NULL part of the code. The problem is that some people may assume you meant line == SetPath.ReadLine() instead of the single '=' sign. When going back over to debug an error, you may not remember that you actually meant the single equal sign and may change it.