Connor Lance
Connor Lance

Reputation: 77

How to do error trapping in a for-loop

Hello I was wondering anyone knew how to do error trapping in a "for" loop I have my loop working and a way to recognize that an invalid number was entered but the invalid number still takes up one of the places in my array

I was wondering if there was a way to get the program to ignore or throw out the invalid input.

        //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--;
    }

Upvotes: 0

Views: 485

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 597385

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;
    }
}

Upvotes: 1

Connor Lance
Connor Lance

Reputation: 77

Credit to ssnobody

The solution I found that fixed my problem was to add Quiz--into the else statement

        //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--;
    }

Upvotes: 0

user2182349
user2182349

Reputation: 9782

//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;
    }
}
  • Updated to use QuizN as the array index, thank you

Upvotes: 0

Related Questions