2016-07-30 101 views
0
int OnLoad() { 
cout << "Hi whats your name? "; 
cin >> name; 
system("cls"); 
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl; 
cin >> userInput; 
if (userInput == "yes" || "Yes") { 
    cout << "Yes" << endl; 
} 
else if (userInput == "no" || "No") { 
    cout << "No" << endl; 
} 
else { 
    cout << "I don't understand." << endl; 
} 
return 0; 
} 

int main() { 
OnLoad(); 
system("pause"); 
return 0; 
} 

此代码只返回是回来后,控制台窗口弹出并要求你在这里从僵尸接管城市,即使我输入否,它返回是!为什么这只返回“是”

+1

'|| “是”不符合你的想法。它总是评估为真!你想'if((userInput ==“yes”)||(userInput ==“Yes”))' – drescherjm

+2

我确信有这个问题的数百(如果不是数千)重复,所以我不会发表正式答案。 – drescherjm

+0

谢谢,我其实开始尝试这个,但我认为这是错误的。大声笑。 – Remi

回答

3
if (userInput == "yes" || "Yes") 

实际上意味着

if ((userInput == "yes") || ("Yes")) 

这是逻辑或两个表达式:userInput == "yes""Yes"。第一个是正确的,直接评估为bool。第二个是char*,它将隐式转换为bool。由于它是编译时间字符串,因此它不能是nullptr,这意味着它将始终评估为true。而这反过来又意味着整个条件总是true(这就是逻辑“或”的工作原理)。 正确的代码

if (userInput == "yes" || userInput == "Yes") 

P. S.这就是为什么我总是建议具有最高级别的警告可能(/W4的MSVC,-Wall -pedantic-errors GCC和铛)编制。在这种情况下,大多数编译器都会生成警告。

0

这不是怎么样的||。运营商的作品,如果你只是把“是”为条件,将始终为true

if (userInput == "yes" || userInput == "Yes") { 
    cout << "Yes" << endl; 
} 

的原因是因为优先

userInput == "yes" 

userInput == "Yes" 

得到评估||之前(逻辑OR)