0

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!

3 Answers3

3
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)

Ben Steffan
  • 1,095
  • 12
  • 16
0

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();
  }
Rama
  • 3,222
  • 2
  • 11
  • 26
0

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++

Community
  • 1
  • 1
partyd
  • 972
  • 1
  • 12
  • 11
  • since the value is 102 it still falls outside the invalid input like 10 but why is it looping? it does not happen to 10 though.. and yep i have to use try and exception for this – Newbie ICT IS Apr 04 '17 at 14:55