C逻辑or在if中

C逻辑or在if中,c,eclipse-cdt,C,Eclipse Cdt,我知道我的C语言不是很好,但我认为我可以做到这一点: if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0) type以char*的形式出现,我已经用条件的第一部分测试了这段代码。它工作得很好。如果我有条件的第二部分,并且我的type包含“in”就可以了,但是如果这三个条件都可用,如果我输入“out”,没有跳过if。这是为什么?您的代码: if(strlen(type) == 0 || strcmp(type

我知道我的C语言不是很好,但我认为我可以做到这一点:

if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0)
type
char*
的形式出现,我已经用条件的第一部分测试了这段代码。它工作得很好。如果我有条件的第二部分,并且我的
type
包含
“in”
就可以了,但是如果这三个条件都可用,如果我输入
“out”
,没有跳过if。这是为什么?

您的代码:

if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0){
    " your code-1"
}
else{
    " your code-2"
}
相当于:

if(strlen(type) == 0 ){
    " your code-1"
}
else{
  if(strcmp(type,"in")!=0){
      " your code-1"   
  }
  else{
      if(strcmp(type,"out")!=0){
            " your code-1"   
      }
      else{
            " your code-2"
      }
  }
}
关键是如果您有第一个
if()
执行,如果string
type
有一些内容,那么else永远不会执行。因为空字符串(在else部分)不能等于
“in”
“out”
。所以,如果字符串不为空,您总是可以选择执行“code-1”,如果字符串为空(即长度=0),则不执行任何操作

编辑:

我想你想要的是,如果
type
string是“in”,那么执行“code-1”。如果type是“out”,那么执行第二个code-2。比如:

if(strlen(type) == 0 ){

}
else{
  if(strcmp(type,"in")!=0){
      " your code-1"   
  }
  else{
      if(strcmp(type,"out")!=0){
            " your code-2"   
      }
  }
}
你可以这样做:

flag = 'o';// this will save string comparison  again
if(strlen(type) == 0 || strcmp(type,"in")==0 || 
                       strcmp(type,"out")!=0 && !(flag='?')){
   "code-1"
}
else{
       if(flag=='o'){ //no strcmp needed
          "code-2"
       }
}
根据我的逻辑,它的运行方式如下:

:~$ ./a.out 
Enter string: in
in 
:~$ ./a.out 
Enter string: out
out 
:~$ ./a.out 
Enter string: xx
:~$ 

如果
类型
为空,或者
类型
包含“in”或“out”,则将执行分支

给定表达式
a | | b
,以下为真:

  • 操作数从左到右求值,这意味着首先求值
    a
  • 如果
    a
    的计算结果为非零(true),则整个表达式的计算结果为true,而
    b
    不计算
  • 如果
    a
    的计算结果为零(false),则计算
    b
  • 如果
    a
    b
    的计算结果均为零(false),则整个表达式的计算结果为false;否则,表达式的计算结果为true
因此,如果
type
包含字符串“out”,那么

  • strlen(type)==0
    计算为
    false
    ,这意味着我们计算
  • strcmp(输入“in”)!=0
    ,其计算结果为
    false
    ,表示我们进行计算
  • strcmp(键入“out”)!=0
    ,其计算结果为
    true
    ,因此
  • 树枝被拿走了
根据你所说的你期待的,听起来你对上一次测试的感觉是错误的,而且你真的想要

if( strlen( type ) == 0 || 
    strcmp( type, "in" ) != 0 || 
    strcmp( type, "out" ) == 0 )
{                      // ^^ note operator
  ...
}

如果
类型
为空,如果
类型
包含“in”,或者
类型
不包含“out”,这将进入分支

在任何一点上,
类型可以是“in”、“out”或两者都不是。因此,无论发生什么情况,最后两个条件中的一个将匹配。是的,但如果
type
out
“或”表示任何条件为真,则第二个条件将为真。您可能需要&&-和这里。@GrijeshChauhan粗略地看一下看起来还可以。可能想进一步说明OP如何修复它。@GrijeshChauhan我不确定您是否需要标志(您实际上是指带有单个标志的
flag='x'
)。我会用一系列的
if-else-if
来完成它。尽管如此,OP还是很可能做到了,不管怎样。