簡體   English   中英

猜詞:I / OC邏輯錯誤

[英]Guess the word: I/O C logic error

相當簡單的程序:

int main (void)
    {
    int i = 0, length=0;
    char password[] = SECRET;
    char guess[10];

    for (i=0; i<3; i++){
        printf( "Enter the password: " );
        fgets (guess, 10, stdin );
        length=strlen(guess);
        guess[length]='\0';
        if(strcmp( guess, password ) == 0 ){
          printf("\aYou got it right!\n" );
          return 0;
          }
          else printf("You wrote %s Incorrect guess\n\n", guess);
    }
    puts("Sorry, you're all out of guesses");

    return 0;

}

但這是行不通的。

即使在奇怪的情況下,我也可以讓程序說:“您猜到了'black'。很抱歉,密碼是'black'。”認為可能存在一些隱藏字符,空格,垃圾信息或其他任何問題。字符串比較,但是我似乎找不到它!

如果您學習使用調試器,則可能會看到fgets()返回的字符串包含換行符,該字符串與您要比較的字符串不匹配。

這段代碼的意義是什么:

length=strlen(guess);
guess[length]='/0';

首先,我只能假設您的意思是\\0而不是/0 其次, strlen()通過找到空終止符來工作。 那么找到終止符然后在相同位置寫入終止符有什么意義呢?

而不是:

 length = strlen(guess);
 guess[length]='\0';  

您應該這樣做:

char *s = strchr(guess, '\n');
if (s) {  
    // new line is found  
    *s = 0;  
} else {  
    // user has exceeded max chars  
    guess[sizeof(guess) - 1] = 0;  
}  

我建議您使用strncmp而不是strcmp以避免緩沖區溢出攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM