当下面的代码出现在cin语句中时:如果我输入-1,它仍会运行我在上一个if if部分中找到的invalidSelectorError()...即使该部分应该传递,如果mainMenuSelector等于-1
为什么?
(顺便说一下,在invalidSelectorError()运行之后,while循环包含一切正常,程序会按预期终止。)
int mainMenuSelector;
while(mainMenuSelector != -1){
cout << "--- MAIN MENU -----------------" << endl;
cout << "[1] Create New Contact" << endl;
cout << "[2] View Existing Contacts" << endl;
cout << "[3] View or Edit Data Fields" << endl;
cout << "-------------------------------" << endl;
cout << "Or just press ENTER to quit." << endl;
cout << "-------------------------------" << endl;
cout << "Selection: ";
mainMenuSelector = -1;
cin >> mainMenuSelector;
cin.ignore();
if(mainMenuSelector == 1){
contactCreator();
}else if(mainMenuSelector == 2){
contactViewer();
}else if(mainMenuSelector == 3){
dataFieldViewer();
}else if(mainMenuSelector != 1 ||
mainMenuSelector != 2 ||
mainMenuSelector != 3 ||
mainMenuSelector != -1
){
invalidSelectorError();
}
}
return 0;
答案 0 :(得分:4)
您应该使用&&
代替||
:
if(mainMenuSelector != 1 &&
mainMenuSelector != 2 &&
mainMenuSelector != 3 &&
mainMenuSelector != -1
){
答案 1 :(得分:0)
这是因为在这一部分:
else if(mainMenuSelector != 1 ||
mainMenuSelector != 2 ||
mainMenuSelector != 3 ||
mainMenuSelector != -1
){
invalidSelectorError();
您正在使用||。因此,只要由||&f; s分隔的四个语句中的一个是真的(并且由于显而易见的原因,情况总是如此),那么您的代码将在&#39;之后输入代码块。如果&#39;