簡體   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