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