如何跳到文件中的新行并重复循环?

时间:2013-10-23 09:43:04

标签: c++ loops fstream

我正在尝试从一个看起来像这样的文件中读取数据:

1 1 2007 12 31 2006
12 31 2007 1 1 2008
1 3 2006 12 15 2006
2 29 1900 3 1 1900
9 31 2007 10 28 2009

我正在使用一个函数以3 int个为一组读取它,因为这些值应该是日期,每行有2个日期。如果该对的第一个日期返回错误,我需要跳到下一行并重复从那里开始的循环,如果没有错误,只需评估下一个组。错误的文件和bool变量作为参考参数传递给Get_Date()函数,因此它们会在函数外部相应地更改。我尝试使用ignore()break语句,如下所示:

while (infile) {
   Get_Date(infile, inmonth1, inday1, inyear1, is_error);
   if (is_error == true){
      infile.ignore(100, '\n');
      break;
   } 
   if (is_error == false) {
      Get_Date(infile, inmonth2, inday2, inyear2, is_error);
      if (is_error == false) {
         Get_Date(infile, inmonth2, inday2, inyear2, is_error);
         other stuff; 
      } 
   }    
}

这使得整个程序在获得1个错误后终止,在第4行,因为2月仅在闰年中有29天。我认为break会将控制权返回到最近的循环,但这似乎并不是正在发生的事情。

1 个答案:

答案 0 :(得分:0)

一旦发现错误,您可以使用continue跳过执行剩余的周期:

while (infile) 
{
    Get_Date(infile, inmonth1, inday1, inyear1, is_error);
    if (is_error)
    {
        //Skip the rest of the line  (we do not know how long it is)
        infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
        continue; //Skip the rest of the cycle
    } 

    Get_Date(infile, inmonth2, inday2, inyear2, is_error);
    if (is_error) { continue; } //Skip the other stuff if we have error

    otherStuff(); 
}

您可以在跳转语句下找到更多信息:http://www.cplusplus.com/doc/tutorial/control/