如果语句错误地读取字符串,则始终在第一个条件下返回

我正在编写一个带字符串变量的错误检查函数,我需要它是“ Y”,“ N”,“ y”或“ n”之一。我的问题是,字符串变量始终设置为“ y”,这表明无论变量接收什么输入,if语句都不会超出第一个条件。如果有明显的错误,例如我在使用'||'运算符,如果有人可以告诉我,将对我有很大帮助。

if (string == "y" || "Y") { //If 'yes'...
    string = "y"; //Standardise input for later use
    return 1; //Error check successfully passed
}
else if (string  == "n" || "N") { //If 'no'...
    string = "n"; //Standardise input for later use
    return 1; //Error check successfully passed
}
else { //If erroeneous input...
    return 0; //Error check not passed
} 
评论
  • Ula
    Ula 回复

    string == "y" || "Y" doesn't do what you think it does: it compares string against "y", and then ORs the result of that with "Y". Since "Y"' is non-zero, it always evaluates totrue`.

    正确的代码是:

    string == "y" || string == "Y"