Reputation: 33
I'm just revising some file i/o for C++. Writing a program that prints its own source code to the terminal without comments
Here are the loops in question WORKING with if statements
while (!inputstream.eof())
{
if(in_comment == false)
{
inputstream.get(temp);
if(temp == '/')
{
inputstream.get(temp1);
if (temp1 == '*')
{
in_comment = true;
}
else
{
inputstream.putback(temp1);
}
}
cout << temp;
}
if(in_comment == true)
{
inputstream.get(temp);
if(temp == '*')
{
inputstream.get(temp);
if (temp == '/')
{
in_comment = false;
}
}
}
}
And here they are NOT working with while loops
while (!inputstream.eof())
{
while(in_comment == false)
{
inputstream.get(temp);
if(temp == '/')
{
inputstream.get(temp1);
if (temp1 == '*')
{
in_comment = true;
break;
}
else
{
inputstream.putback(temp1);
}
}
cout << temp;
}
while(in_comment == true)
{
inputstream.get(temp);
if(temp == '*')
{
inputstream.get(temp);
if (temp == '/')
{
in_comment = false;
}
}
}
}
I would have expected the eof marker to cause the program to break out of the outer while loop but it doesn't. Why is this?
Thanks
Upvotes: 0
Views: 165
Reputation: 1774
Your inner loops do not break on eof so you get an endless loop - simple as that. The outer loop only gets a chance to break when the inner loops are left. The working example has no inner loops, so the outer loop can end.
Upvotes: 3