如何在for循环中进行错误捕获

时间:2015-07-07 01:10:17

标签: c++ arrays loops for-loop error-handling

您好我想知道如何知道如何在" for"中进行错误捕获。环 我有循环工作,并且有一种方法可以识别输入了无效的数字但是无效的数字仍然占据了我的数组中的一个位置

我想知道是否有办法让程序忽略或丢弃无效输入。

        //for loop to collect quiz scores
for (Quiz=0 ; Quiz < 4; Quiz++) //loop to input and add 4 quiz grades
{
    cout << "Enter grade for Quiz " << QuizN++ << " ";  //output to screen 
    cin >> Qscore[Quiz];    //array in action taking scores inputted and assigning it a position inside the array

    if (Qscore[Quiz] >= 0 && Qscore[Quiz] <= 10)
        QTotal = QTotal + Qscore[Quiz];
    else
    {
        cout << "Please enter a score between 0 and 10" << endl;
        QuizN--;
    }

3 个答案:

答案 0 :(得分:1)

for(Quiz = 0; Quiz < 4;) //loop to input and add 4 quiz grades
{
    cout << "Enter grade for Quiz " << Quiz+1 << " ";  //output to screen 
    cin >> Qscore[Quiz];    //array in action taking scores inputted and assigning it a position inside the array

    if ((Qscore[Quiz] >= 0) && (Qscore[Quiz] <= 10))
    {
        QTotal += Qscore[Quiz];
        ++Quiz;
    }
    else
    {
        cout << "Please enter a score between 0 and 10" << endl;
    }
}

答案 1 :(得分:0)

//for loop to collect quiz scores
for (Quiz=0 ; Quiz < 4; Quiz++) //loop to input and add 4 quiz grades
{
    cout << "Enter grade for Quiz " << QuizN << " ";  //output to screen 
    cin >> score;  // Save the entered score

    // Test to see if the score is valid
    if (score >= 0 && score <= 10) {
        // If the score is valid, add it into the array and update the total
        Qscore[QuizN] = score;
        QTotal = QTotal + score;
        QuizN++;
    } else {
        cout << "Please enter a score between 0 and 10" << endl;
    }
}
  • 更新为使用QuizN作为数组索引,谢谢

答案 2 :(得分:0)

归功于ssnobody

我发现修复我的问题的解决方案是将Quiz--添加到else语句

        //for loop to collect quiz scores
for (Quiz=0 ; Quiz < 4; Quiz++) //loop to input and add 4 quiz grades
{
    cout << "Enter grade for Quiz " << QuizN++ << " ";  //output to screen 
    cin >> Qscore[Quiz];    //array in action taking scores inputted and assigning it a position inside the array

    if (Qscore[Quiz] >= 0 && Qscore[Quiz] <= 10)
        QTotal = QTotal + Qscore[Quiz];
    else
    {
        cout << "Please enter a score between 0 and 10" << endl;
        QuizN--;
        Quiz--;
    }