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

How to skip to a new line in a file and repeat loop?

本文关键字:循环 新行 何跳 文件      更新时间:2023-10-16

我正在尝试从如下所示的文件中读取数据:

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 s 为一组读取它,因为这些值应该是日期,每行有 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 天。我以为中断会将控制权返回到最近的循环,但这似乎不是正在发生的事情。

一旦发现错误,您可以使用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(); 
}

您可以在以下位置的 Jump 语句下找到更多信息: http://www.cplusplus.com/doc/tutorial/control/