Newbie ICT IS
Newbie ICT IS

Reputation: 9

try catch repeating loop

Hey all this is my code

void Student::studentMenu() {
    int choiceInput;
    const string ErrorMsg;
    cout << "-------------Student Menu--------------" << endl;
    cout << "(1)Start Quiz" << endl;
    cout << "(2)View History Score Table" << endl;
    cout << "(0)Exit" << endl;
    cout << "Option: " << endl;
    try {
        cin >> choiceInput;

        if (choiceInput < 0 || choiceInput>2 || !cin)
        {
            throw (ErrorMsg);
        }

        while (choiceInput != 0) {
            switch (choiceInput) {
            case 1:
                generateQuiz();
                break;
            case 2:
                break;
            case 0:
                break;
            }
            break;
        }
    }
    catch (string msg)
    {
        cout << "Please only enter valid integer from 0-3" << endl;
        Student::studentMenu();
    }
}

Basically it checks the user input and throw an exception if its a non integer larger than 3. After displaying the error message, it should redirect back to the student menu() page. The output is intended when i enter an integer like 5 but when i enter a char 'f' it keeps looping the error message

Please help me thanks!

Upvotes: 0

Views: 2053

Answers (3)

Rama
Rama

Reputation: 3305

You need to initilize you choiceInput variable with an invalid value:

int choiceInput = -1;

And in you catch use cout.flush() to be sure that you clean the buffers before calling to studentMenu():

  catch (string msg)
  {
    cout << "Please only enter valid integer from 0-3: " << choiceInput << endl;
    cout.flush();
  }

Upvotes: 0

Ben Steffan
Ben Steffan

Reputation: 1125

cin >> choiceInput;

What happens when the input is not a parsable integer, cin does not automatically skip over it. That means that you get stuck on that value: You try to read it, it fails, you go one iteration deeper, you try to read it, it fails, etc. To fix this, you should ignore the wrong characters in case reading fails (e.g. !cin returns true). Typically, this would look something like this:

if (!cin) {
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} //proceed

(cin.clear() is required to clear the failbit, so that !cin becomes false again)

Upvotes: 3

partyd
partyd

Reputation: 1043

choiceInput is an integer and the ascii value of 'f' is 102 which is > 2. I would recommend you should add some more checks on choiceInput to make sure it is an integer and not a character.

See

How to check if input is numeric in C++

Upvotes: 0

Related Questions