Validating User Input inside while loop - C++ Statement

C++ examples for Statement:while

Description

Validating User Input inside while loop

Demo Code

#include <iostream>

int main(int argc, const char *argv[]) {
    int passes = 0;
    int failures = 0;
    int studentCounter = 1;
    int result;//from w w  w.j a  va 2 s .c om

    while (studentCounter <= 10) {
        std::cout << "Enter result (1 = pass, 2 = fail) ";
        std::cin >> result;

        if (result == 1)
            passes++;
        else if (result == 2)
            failures++;
        else
            continue;

        studentCounter++;
    }

    std::cout << "Passed " << passes << "\nFailed " << failures << std::endl;

    // determine whether more than 8 students passed
    if (passes > 8) 
       std::cout << "more than 8!" << std::endl;
    return 0;
}

Result


Related Tutorials