c++ - 遇到错误时循环不会中断

标签 c++ loops fstream

我有一个文件,其中包含每个人的分数。分数的数量因行而异。我试图通过执行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;
       }
  }
}

最佳答案

该代码工作正常。文件名拼写错误

关于c++ - 遇到错误时循环不会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61370898/

相关文章:

c++ - 对此 cpp 代码使用 cl.exe (Visual Studio 2008) 编译错误

c++ - 使用 ncurses 显示 wchar_t

c++ - 流不附加换行符

c++ - 这个 `main` 的定义有多合法?

c++ - 如何修复错误 "was not declared in this scope"?

javascript - 如何使用闭包在循环中使用 then()

java - 为什么我在循环中的第一个 .nextline 被跳过然后下一次没有跳过?以及如何阻止它覆盖?

R - 如何在列表中循环打印进度?

c++ - 使用相同的流对象写入文件流或字符串流

c++ - 如何从文本文件的中间读取