0

I have a code like ;

bool exitRunner=true;
unsigned short int choiceNum=0;

int main(int argc, const char * argv[]) {
    while(exitRunner)
    {

        cout << "Please specifiy the choice that you want to proceed \n";
        cout <<"1: Encryption \v 2: Decryption \v 3: Exit \n";
        cin >> choiceNum;
        switch (choiceNum)
        {
            case 1:
            {
             //Encryption
             break;
            }
            case 2:
            {
             //Decryption
             break;
            }
            case 3:
            {
                exitRunner=false;
                break;
            }
            default:
            {

                cout << "Invalid Input \n";
            }
        }

    }

But after I enter a invalid input like a character , the program enters in an infinite loop, it doesn't ask any input again.

The output looks like;

Please specifiy the choice that you want to proceed 
1: Encryption  2: Decryption  3: Exit 
Invalid Input 
Please specifiy the choice that you want to proceed 
1: Encryption  2: Decryption  3: Exit 
Invalid Input  
Please specifiy the choice that you want to proceed 
1: Encryption  2: Decryption  3: Exit 
Invalid Input 

And actually, although I enter a valid input (1,2,3) ,sometimes it enters in an infinite loop again. By the way, I am talking about the input for $choiceNum.

So, what is the in the code and how can I fix it ? or Do you have any idea what may cause the problem ?

1 Answers1

0

If the input stream encounters an error (like bad input), it will no longer block. It needs to be reset before it can be used again, or you get the infamous infinite loop.

It's been awhile since I've coded c++ though, and I can't remember the exact function used to reset the stream.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117