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

How to do error trapping in a for-loop

本文关键字:错误 for 循环      更新时间:2023-10-16

你好,我想知道有谁知道如何在"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--;
    }
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;
    }
}
//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作为数组索引,谢谢

归功于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--;
    }