简体   繁体   English

字符比较始终为假c

[英]char comparison always false c

I'm trying to do a simple do while loop where any letter other than 'y' or 'n' is invalid and the loop is repeated. 我正在尝试做一个简单的do while循环,其中除'y'或'n'以外的任何字母都是无效的,并且重复循环。 Does anyone know why this loop always evaluates to false? 有谁知道为什么这个循环总是评估为假? Even when a valid character is entered? 即使输入了有效字符?

char user_response[2];

do {
    printf("\nDo you want to process another range (y or n): ");
    scanf("%1s", user_response);
    user_response[0] = tolower(user_response[0]);
}
while (user_response[0] != 'y' || user_response[0] != 'n');

return user_response[0];

You should change || 您应该更改|| to &&. 至 &&。

You want to use "&&" (and) instead of "||" 您要使用“ &&”(和)而不是“ ||” (or). (要么)。

You have two tests here: "does the response not equal y", "does the response not equal n". 您在此处进行了两个测试:“响应不等于y”,“响应不等于n”。 As the response cannot be "y" and "n" at the same time, at least one of those tests will always be true, and by using "or" your while test will always evaluate to true. 由于响应不能同时为“ y”和“ n”,因此至少其中一个测试将始终为真,并且通过使用“或”,while测试将始终为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM