输入无效输入会导致循环进入无限循环

时间:2016-07-14 04:34:43

标签: c++ loops switch-statement

我有一个类似的代码;

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";
            }
        }

    }

但是在我输入一个像字符一样无效的输入后,程序进入一个无限循环,它不会再次询问任何输入。

输出看起来像;

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 

实际上,虽然我输入了一个有效的输入(1,2,3),但有时它会再次进入无限循环。 顺便说一句,我在谈论$ choiceNum的输入。

那么,代码中有什么,我该如何解决?或者你知道可能导致问题的原因吗?

1 个答案:

答案 0 :(得分:0)

如果输入流遇到错误(如输入错误),它将不再阻止。它需要重置才能再次使用,否则你会得到臭名昭着的无限循环。

自从我编写c ++以来已经有一段时间了,我记不起用于重置流的确切函数了。

相关问题