【问题标题】:Loop isn't breaking when it encounters error遇到错误时循环不会中断
【发布时间】:2020-04-22 17:04:29
【问题描述】:

我有一个文件,其中包含每个人的分数。分数的数量因行而异。我试图通过 while(file>>array[i]) 将每个人的数字存储到数组中,因为我将数组声明为整数,所以当它尝试读取单词时,while(file>>array[i]) 不应该中断吗?这样做的正确方法是什么?

John Carter: 34 51 22 15 45
Ron Wilder: 32 33 23
John Carter: 1 2 3 4
Ron Wilder: 24 25 1 2 3 4

这是逻辑。当这个程序运行时,我会进行边界检查。

void storeNum(ifstream & file)
{
   int i =0, j= 0; 
   int JohnArray[10] = {0}; //store numbers for John
   int RonArray[10] = {0};    //Stores numbers for Ron
   string stringVariable;
   while (getline(file, stringVariable,':')) //file is a ifstream variable 
   {
      if (stringVariable == "John Carter")
      {
           while (file >> JohnArray[i])   //This should break when it encounter non integer
           {
                 i++; 
           }
           if (file.fail())
          {
              file.clear();     //clear fail bit
          }
      }
      else if (stringVariable == "Ron Wilder")
      {
          while (file >> RonArray[j])    //store numbers for Ron
           {
                 j++;
            }
           if (file.fail())
           {
               file.clear();   //clear failbit
            }
      }
      else 
       {
          continue;
       }
  }
}

【问题讨论】:

  • 你的问题是什么? Demo
  • 为什么您认为该程序不起作用?它似乎在我的电脑上运行良好。
  • @Jarod42 get line 也在抢号码
  • @RSahu 在打印出数组时仅显示 0。编辑:文件中的名称拼写正确

标签: c++ loops fstream


【解决方案1】:

代码运行良好。文件名拼写不正确

【讨论】:

    【解决方案2】:

    一种方法是使用异常处理,伪代码是:

    try{
      //your_code, ie reading from file
    }catch(exception){
      //print your error here
    }
    

    【讨论】:

    • 只有在您期望代码抛出异常时才有效。 OP 的代码并非如此。
    • "catch(exception)" - 为了防止对象切片,您通常希望始终通过 (const) 引用捕获异常。所以(也是伪代码),catch(const& exception).
    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2019-08-29
    • 2015-12-16
    • 2021-05-15
    • 1970-01-01
    • 2021-01-30
    • 2013-11-01
    相关资源
    最近更新 更多