修改包含break语句的while循环

时间:2019-04-14 18:25:22

标签: c++

我目前正在尝试编写一个循环,以继续使用getline从输入文件中提取每一行,并一直运行直到它检测到段落的结尾。

我发现这是参考:

while (getline(inFile, line))
{
   if (line.empty())
      break;

  else
  {
     for (int j = 0; j < line.length(); j++)
     {
        //Doing stuff here
     }
  }
}

我已经对此进行了测试,并且运行正常。但是,我不允许在我的作业中使用break语句。

我认为我可以做这样的事情:

while (getline(inFile, line))
{
    while (!line.empty())
    {
        for (unsigned int i = 0; i < line.length(); i++)
        {
            //Do stuff
        }
     }
 }

但是,当循环首次迭代时,程序最终会崩溃。我想知道是否有人可以解决该问题

2 个答案:

答案 0 :(得分:2)

这是解决问题的方法:

while (getline(inFile, line) && !line.empty()) { ... }

它具有完全相同的效果,并且可以提高可读性。您的方法的问题在于,它会导致无限循环。 line.empty()评估false的事实并不影响那里的外部while

答案 1 :(得分:1)

以下内容还演示了如何使用字符串流进行测试。 exec包含3个测试代码段。

int exec(int , char** )
{
   int retVal = 0;
   cout << "\n\n";

   string s =
      "  now is the time\n"
      "  for all good men\n"
      "\n"                       // empty line
      "  to come to the aid \n";  // eof()

   // solution 1 has infinite loop
   if(0) // disable
   {
      stringstream ss;
      ss << s;      // load ss

      string line;
      while (getline(ss, line))
      {
         while (!line.empty())
         {
            for (uint j=0; j < line.length(); ++j)
               cout << line[j];
         }
         cout << endl;
      }
   }

   // solution 2 exits too soon, line 3 is empty, line 4 dropped
   {
      cout << "\n\n";
      stringstream ss;
      ss << s;      // load ss

      string line;
      while (getline(ss, line) && !line.empty())
      {
         cout << line << endl;
      }
   }
   // output: 
   //  now is the time
   //  for all good men


   // solution 3 - small test effort, but seems to work
   {
      cout << "\n\n";
      stringstream ss;
      ss << s;      // load ss

      do
      {
         string line;
         getline(ss, line);  // read a line

         if (!line.empty())       // test it has content
            cout << line << endl; // use when non-empty

      } while(!ss.eof());    // how continue when file has more lines

   } // solution 3 seems to work
   // output: 
   // now is the time
   // for all good men
   // to come to the aid        

   return retVal;
}