繁体   English   中英

无限循环,我不知道为什么

[英]Infinite loop and I don't know why

我想使用两个字符串的比较作为循环的条件,但循环进入无限循环,我不知道为什么。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void input(int a[], char *comando, char *aux) {
    fgets(aux, 35, stdin);
    sscanf(aux, "%s %d  %d", comando, &a[0], &a[1]);
}

int table_size=10;
int ar_temp[2];
char comando[2];
char aux[35];

int main() {

    while((strcmp (comando, "X"))!=0 || (strcmp (comando, "x")!=0)) {
        input(ar_temp, comando, aux);
    }

    return 0;
}

请帮帮我

条件错误,while语句总是评估为true。

while((strcmp (comando, "X"))!=0 || (strcmp (comando, "x")!=0)) 

它应该是:

while((strcmp (comando, "X"))!=0 && (strcmp (comando, "x")!=0)) 

虽然(我不是骆驼)或(我不是狗)...

即使是美洲驼和狗也会对其中一个子条款产生真实的结果,所以,既然真实或任何事情都是真的,那么这个陈述总会导致真实的。

你需要的是(回到你的实际代码,而不是我稍微荒谬的例子):

while ((strcmp (comando, "X") != 0) && (strcmp (comando, "x") != 0)) {
//                                  ^^
//                          and rather than or

你会发现我也是“固定”你的第一个子句,以便使用括号是一致的,移动) ,以0

当然,如果你有任何其他地方你检查comando ,它可能是值得只是单个案例预先,然后你只需要检查小写变体。

暂无
暂无

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

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