0

here is the code

int miscellaneous::printWelcomeScreen(){
    int ch;
    cout<<"Tic Tac Toe"<<endl<<endl;
    cout<<"1. Play Game "<<"2. How to Play "<<"3. Credits "<<endl;
    cout<<endl<<"Enter Your Choice"<<endl;
    cin>>ch;
    choiceSelection(ch);
    return 0;
}

int miscellaneous::choiceSelection(int ch){
    switch(ch){
    case 1: break;
    case 2: showHelp();break;
    case 3: showCredits();break;
    default: {
            cout<<"Wrong Choice dude!! Use your keyboard Properly next time";
            printWelcomeScreen();
            break;
            }
    }
    return 0;
}

When I give a int input, default case works perfectly, But when I give a char input, default case starts running in infinite loop.

Why this is happening? I even tried parsing ch before passing to switch.

Vikas Kumar
  • 2,978
  • 3
  • 14
  • 24
  • You might be better off using `char ch` instead of `int ch` and updating the `switch` to check for characters `'1'`, `'2'`, and `'3'`. – James Adkison Aug 28 '15 at 03:31

2 Answers2

2

You're not checking whether the read failed. And as such, if std::cin fails once, it'll implicitly fail until the situation is handled, resulting in infinite recursion and an eventual stack overflow. Use something like this instead.

int miscellaneous::printWelcomeScreen() {
    int n;
    bool again;

    do {
        again = false;

        std::cout << "Tic Tac Toe\n\n1. Play Game\n2. How to Play\n3. Credits\n\nEnter your choice: ";
        std::cin >> n;
        if(std::cin.fail() || !choiceSelection(n)) {
            again = true;
            std::cout << "Hey! That's not valid input! Try again.\n\n"

            continue;
        }
    } while(again);

    return 0;
}

bool miscellaneous::choiceSelection(int n) {
    switch(n) {
        case 1:
            // ...
            break;

        case...

        default:
            return false;
    }

    return true;
}
3442
  • 8,248
  • 2
  • 19
  • 41
2

When you enter a char value, cin(input) operation fails as, entered something other than the type of ch. So here their is a need to check weather the input operation is failed or not. For this use cin.fail() which will be set on cin fail.

int miscellaneous::printWelcomeScreen()
{
    int ch  = 0;
    cout<<"Tic Tac Toe"<<endl<<endl;
    cout<<"1. Play Game "<<"2. How to Play "<<"3. Credits "<<endl;
    cout<<endl<<"Enter Your Choice"<<endl;
    cin >> ch;
   if(cin.fail() != 0)
   {
       std::cout << "Hey! That's not valid input! Try again.\n\n"
       cin.clear();
       cin.ignore(10000,'\n');
   }
   cout <<  " ch = " << ch << endl;
   choiceSelection(ch);
   return 0;
}

When cin is checked and found failed then need to clean the error flag on cin. Details of it is explained in this link: Why would we call cin.clear() and cin.ignore() after reading input?.

Community
  • 1
  • 1
Sandeep Kumar
  • 336
  • 1
  • 3
  • 9