2017-07-26 43 views
1

所以我在测试时确定while循环运行时运行这个问题。如果一个非整数值输入cin < < a;循环将无休止地执行而不要求进一步的a值,如果输入的是整数,但不是列出的其中一个,它可以正常工作,但我希望它能够解释用户尝试的任何输入。有没有简单的方法来解决这个问题?我认为它与一个int是有关系的,但是我稍后需要一个int语句作为switch语句。While循环对非整数奇怪地响应

int a; 
cout << "What type of game do you wish to play?\n(Enter the number of the menu option for)\n(1):PVP\n(2):PvE\n(3):EVE\n"; 
cin >> a; 
while (!((a == 1) || (a == 2) || (a == 3))) 
{ 
    cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n"; 
    a = 0; 
    cin >> a; 
} 
+0

哇,这么多的括号!你不需要围绕单个'=='测试的测试,你可以通过应用De Morgan的定理,在三个测试中摆脱对:'while(a!= 1 && a!= 2 && a!= 3)'更容易阅读...... –

回答

0

我得到它的工作:

int a; 
cout << "What type of game do you wish to play?\n(Enter the number of the menu option for)\n(1):Player V Player\n(2):Player vComp\n(3):Comp V Comp\n"; 
cin >> a; 
while (a != 1 && a != 2 && a != 3 || cin.fail()) 
{ 
    cout << "That is not a valid gametype. Pick from the following menu:\n(1):Player V Player\n(2):Player vComp\n(3):Comp V Comp\n"; 
    cin.clear(); 
    cin.ignore(256, '\n'); 
    cin >> a; 
} 
4
cin >> a; 

如果此代码失败(和它,如果你提供非整数数据),流将进入无效状态,并cin >> a所有后续调用将没有副作用立即返回,仍处于错误状态。

这是一个我不太喜欢的C++设计决定(也可能是为什么大多数人不喜欢C++中的Streams设计),因为你会希望这会抛出一个错误或者之后返回正常状态,比如在大多数其他语言。相反,它失败了,这是许多程序错误的最大来源。

无论如何,这有两个可能的修复。

第一个是正确检查该流是否仍然有效。像这样:

while (!((a == 1) || (a == 2) || (a == 3))) 
{ 
    cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n"; 
    a = 0; 
    if(!(cin >> a)) break; //Input was invalid; breaking out of the loop. 
} 

这将打破循环,如果输入无效,但使流处于无效状态。

另一种修复方法是将流重置为有效状态。

while (!((a == 1) || (a == 2) || (a == 3))) 
{ 
    cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n"; 
    a = 0; 
    while(!(cin >> a)) { 
     std::cin.clear(); 
     std::cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
     std::cout << "Please only enter Integers." << std::endl; 
    } 
} 

第二个通常是人们需要的方法,但可能会出现第一个更合理的情况。

+1

您当然可以自由地去讨厌C++流的设计,但是您不应该声称代表“大多数人”,特别是当您的反对意见采用陈述的形式时这清楚地表明你不知道设计目标是什么,你不知道如何正确使用它们。 –