经过大量的时间试图让我的其他if语句工作,它只是没有。无论我输入什么内容,该程序都会返回第一个程序。请帮忙。
#include <iostream>
#include <string>
using namespace std;
string arehap;
int main()
{
cout << "Are you happy?" << endl;
cin >> arehap;
if (arehap == "Yes" || "Y")
{
cout << "Good." << endl;
}
else if (arehap == "No" || "N")
{
cout << "Bad." << endl;
}
return 0;
}
答案 0 :(得分:2)
你的问题在于这一行:
if (arehap == "Yes" || "Y")
C ++将此理解为
if ((arehap == "Yes") || ("Y"))
虽然第一次检查(arehap == "Yes"
)可能是假的,但第二次检查 - 只是"Yes"
始终为真。
这种情况发生了,因为"Yes"
被理解为char const*
- 并且此指针显然不是NULL
,而是指向字符'Y'
!