0

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

  • 2
    Compile with all warnings and debug info (`g++ -Wall -Wextra -g`). Then **use the debugger** (`gdb`) – Basile Starynkevitch Dec 27 '14 at 14:21
  • Were you expecting the outer while to be broken while the inner while was still running? If so, that's your problem. It only checks the condition `!inputstream.eof()` at the beginning of each loop: If the outer loop never has a chance to the beginning, it won't be able to check. – Numeri Dec 27 '14 at 14:21
  • Basile Starynkevitch also has a very good suggestion—learn to use a debugger well! Stepping through your code line by line with a variable watch is very, very helpful. (If you use an IDE, it almost certainly has a debugger in it.) – Numeri Dec 27 '14 at 14:24
  • 1
    Also have a look on [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) please. – πάντα ῥεῖ Dec 27 '14 at 15:16

1 Answers1

3

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.

Ole Dittmann
  • 1,764
  • 1
  • 14
  • 22