简体   繁体   English

为什么|| 操作员在我的情况下工作

[英]Why does || operator work in my situation

Why is this an infinite loop using ||为什么这是使用 || 的无限循环logical operator逻辑运算符

char c;
std::cin >> c;
while( c != 'y' || c != 'Y' || c != 'N' || c != 'n') 

but this is not但这不是

while( c != 'y' && c != 'Y' && c != 'N' && c != 'n')

I don't understand why && operator work here because logically thinking ||我不明白为什么 && 运算符在这里工作,因为逻辑思考 || operator is better fit.运营商更适合。

Lets just look at the very smallest part:让我们看看最小的部分:

c != 'Y' || c != 'N'

If c is 'Y' then it is not 'N', if it is 'N' then it is not 'Y'.如果 c 为“Y”则不是“N”,如果为“N”则不是“Y”。 Aka:又名:

c  |  c != 'Y' || c != 'N'
Y  |     1     ||   0      =  1
N  |     0     ||   1      =  1
?  |     1     ||   1      =  1

If your logic always returns 1 no matter what, the loop will run forever.如果您的逻辑无论如何总是返回 1,则循环将永远运行。 I assume you are looking to wait until you get c as one of these values, so write it logically.我假设您希望等到将c作为这些值之一,因此请按逻辑编写。

I want to wait until c is one of ['y', 'Y', ...]我想等到 c 是 ['y', 'Y', ...] 之一

And you might be able to write some nicer code:你也许可以写一些更好的代码:

std::array<char> options = {{'y', 'Y', 'n', 'N'}};

while (std::none_of(std::begin(options), std::end(options), 
         [&c](char check) { return check == c; };)) {
    std::cout << "Hey write the correct character!\n";
}

Untested!未经测试!

You are checking the condition which is always true by using ||您正在使用||检查始终为真的条件operator, ( c != 'y' || c != 'Y' || c != 'N' || c != 'n') operator, ( c != 'y' || c != 'Y' || c != 'N' || c != 'n')

This is always true,because it would always satisfy at-least 3 conditions in your conditional statement.这始终是正确的,因为它始终会满足您的条件语句中的至少 3 个条件。

if your char is n then it would satisfy remaining conditions c!='y' , c!='Y' , c!='N' and similarly for any other character如果您的 char 是n那么它将满足其余条件c!='y'c!='Y'c!='N'并且对于任何其他字符类似

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

相关问题 为什么#ifndef在这种情况下不起作用? - Why does #ifndef not work in this situation? 在这种情况下,::运算符会做什么 - What does the :: operator do in this situation 为什么 std::set 可以与我的自由函数 operator&lt; 一起使用,但不能与我的类成员函数 operator&lt; 一起使用? - Why does std::set work with my free function operator<, but not my class member function operator<? 操作员重载如何工作,为什么在我的情况下不起作用? - How does operator overloading work, and why doesn't it work in my case? 为什么显式运算符 std::string 不起作用 - why explicit operator std::string does not work 为什么赋值运算符不能按预期工作? - Why does assignment operator not work as expected? 为什么运算符“ new”需要一个指针才能起作用? - Why does operator “new” require a pointer to work? 为什么这种运算符重载方法在这里不起作用? - Why does this method for operator overloading not work here? operator&lt;&lt; 的全局重载不起作用,为什么? - Global overload of operator<< does not work, why? 为什么这个重载的 operator<< 以意想不到的方式工作? - Why does this overloaded operator<< work in an unexpected way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM