2016-11-14 55 views
2
void verification() { 
    char pass[50]; 

    printf(" Enter Password : "); 
    fgets(pass, 50, stdin); 

    if (pass != 'aaanc6400') { \\ Warning message in here 
     printf("\n Invalid Password.. Please enter the correct password. \n\n"); 
     verification(); 
    } 
    info(); 
} 

當我編譯該程序,在標記行它示出警告「字符常數太長其類型」,也是「指針和整數之間的比較」。然後當我運行代碼並輸入正確的密碼時,它仍會打印密碼錯誤。我究竟做錯了什麼?字符常數太長其類型(與fgets)

+0

@A。色調。是的,我試過了。然後出現另一個警告消息「比較字符串文字結果在未指定的行爲」 –

+4

''aaanc6400''是一個多字節字符常量,這當然不是你想要的。您需要使用雙引號(用於c字符串)並使用strcmp()來比較它們。 –

+0

@你只在單個字符上使用單引號,而不是在字符串上(儘管我想P.P.的解釋更好)。儘管對上述問題的回答解決了這個問題,但我並不認爲這是一個確切的發表。 – Lehue

回答

3

你需要:通過pass[strlen(pass) - 1] = '\0';(後fgets)從fgets

  • 初始化char pass[50] = "";
  • 刪除\n - 這可以幫助您比較字符串稍後的。
  • if (pass != 'aaanc6400')這是完全錯誤的。使用strcmp對於字符串比較,和雙引號字符串"aaanc6400"

從@chux:這是更好地使用strcspn,而不是strlen剪掉了\nfgets

char pass[50] = ""; 
    printf(" Enter Password : "); 
    if(fgets(pass, 50, stdin) == NULL) 
    { 
     perror("fgets error"); 
     return; 
    } 
    pass[strcspn(pass, "\n")] = 0; // trim \n 

    if(strcmp(pass, "aaanc6400")) { 
     printf("\n Invalid Password.. Please enter the correct password. \n\n"); 
     verification(); 
    } 
+0

試過了。警告沒有顯示出來,但是每次我輸入正確的密碼時,都會顯示無效的密碼 –

+0

是否已在我的答案中刪除了'\ n'(第2個點)? – artm

+0

如何刪除'\ n'? –

3

您無法將字符指針與字符串文字進行比較。

你應該寧可做的是:

if (strcmp(pass, "aaanc6400") == 0) 
{ ... } 
+0

如果你不從'fgets'中刪除'\ n',那麼'strcmp'將不起作用 – artm

5

的警告關於你聲明你有一個很長的角色。

'aaanc6400' 

是9個字符長的字符,編譯器會發出警告,它可能是一個拼寫錯誤。這是正確的。

在C中,我們使用的字符和"雙引號單引號'字符串這與'\0'字符終止字符數組。

所以你必須用"aaanc6400"替換'aaanc6400'並使用strcmp。記得! fgets也可能讀取\n,因此您可以將輸入與"aaanc6400""aaanc6400\n"進行比較。這個解決方案對於學生項目就足夠了。

1

verification功能存在多個問題:

  • 'aaanc6400'是一個多字符常量,不能攜帶使用的過時的建築。您可能打算比較從用戶讀取的字符串與字符串"aaanc6400":您應該使用strcmp()

  • 您應該檢查返回值fgets():在文件結尾或讀取錯誤時,它返回NULL並且數組內容不確定。

  • 如果發生錯誤,您應該使用循環而不是遞歸。

這裏是一個修正版本:

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

void verification(void) { 
    char pass[50]; 

    printf(" Enter Password: "); 
    for (;;) { 
     fflush(stdout); 
     if (fgets(pass, 50, stdin) == NULL) { 
      printf("unexpected end of file\n"); 
      exit(1); 
     } 
     pass[strcspn(span, "\n")] = '\0'; // remove the newline if present 
     if (strcmp(pass, "aaanc6400") == 0) { 
      // correct password, stop prompting. 
      break; 
     } 
     printf("\n Invalid Password. Please enter the correct password: "); 
    } 
    info(); 
} 
相關問題