C++ - 简单 - 嵌套,而循环永远不会终止

C++ - Simple - nested while loops never terminate?

本文关键字:永远 终止 循环 简单 嵌套 C++      更新时间:2023-10-16

我只是在修改一些文件的 I/O C++。编写一个程序,将自己的源代码打印到终端而不带注释

以下是有问题的循环 使用 if 语句

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;
            }
        }
    }
}

在这里,他们不使用while循环

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;
            }
        }
    }
}

我本来希望 eof 标记会导致程序脱离外部 while 循环,但它没有。这是为什么呢?

谢谢

你的内部循环不会在 eof 上中断,所以你会得到一个无限循环 - 就这么简单。只有当内循环离开时,外循环才有机会中断。工作示例没有内部循环,因此外部循环可以结束。