C逻辑或if
我知道我在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()
执行,如果字符串type
有东西,那么点就是,否则永远不会执行。 因为空字符串( 在其他部分中 )不能等于"in"
或"out"
。 因此,如果string 不为空 ,您总是可以选择执行“code-1”,如果string为空( 即length = 0 )则无需执行任何操作。
编辑:
我想你想要类似字符串是“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 :~$
如果type
为空,或者type
包含“in”或“out”,则将采用分支。
给定表达式a || b
a || b
,以下是真实的:
- 操作数从左到右进行评估,这意味着首先评估
a
; - 如果计算结果为非零(true),则整个表达式的计算结果为true,并且不计算
b
; - 如果计算结果为零(假),则评估
b
; - 如果
a
和b
评估为零(false),则整个表达式的计算结果为false; 否则,表达式的计算结果为true;
因此,如果type
包含字符串“out”,那么
-
strlen(type) == 0
计算结果为false
,这意味着我们评估 -
strcmp(type, "in") != 0
,计算结果为false
,表示我们评估 -
strcmp(type, "out") != 0
,计算结果为true
,所以 - 分支被采取
根据你所说的你所期待的,听起来你觉得上次测试错了,你真的想要
if( strlen( type ) == 0 || strcmp( type, "in" ) != 0 || strcmp( type, "out" ) == 0 ) { // ^^ note operator ... }
如果type
为空,如果type
包含“in”,或者type
不包含“out”,则将进入分支。