【问题标题】:How to skip to a new line in a file and repeat loop?如何跳到文件中的新行并重复循环?
【发布时间】:2013-11-01 12:35:35
【问题描述】:

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

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

【问题讨论】:

  • 如果第一个日期未能正确读取,您应该调用std::getline() 来切到行尾。如果第二个失败了,此时你应该已经消耗到了行尾,所以你无事可做......
  • 请通过删除代码中所有多余的空格来提高代码的可读性。

标签: c++ loops fstream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-05-06
    • 2013-12-21
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2017-02-14
    • 2017-07-23
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多