2014-09-04 20 views
-4

该代码有什么问题?该代码有什么问题?

我的代码直接转到“其他”,即使我输入正确的密码,有人能告诉我为什么吗?

#include <stdio.h> 

int main(void){ 
    char password[50]; 
    printf("Type your password: "); 
    fgets(password, sizeof(password), stdin); 
    if(password == "test"){ 
     printf("Login successfull\n"); 
    }else{ 
     printf("Access denied\n"); 
    } 
    return 0; 
} 

编辑:

感谢你的一切,现在的代码工作。现在 我会一定要做到的是,以下

工作代码接下来的时间:

#include <stdio.h> 
#include <string.h> 
int main(void){ 
    char password[50]; 
    printf("Type your password: "); 
    fgets(password, sizeof(password), stdin); 
    password[strlen(password)-1]='\0'; 
    if(strcmp(password, "test") == 0){ 
     printf("Login successful\n"); 
    }else{ 
     printf("Access denied\n"); 
    } 
    return 0; 
} 
+3

请勿使用'=='比较字符串。使用'strcmp'。 – 2014-09-04 01:07:57

+1

@ROZ至少在C中,'=='不会比较代码中的两个字符串。相反,'=='会比较指针。 – tay10r 2014-09-04 01:09:31

回答

2
  1. password删除\n。接受密码(fgets后)做到这一点: password[strlen(password)-1]='\0';

  2. 对于字符串比较使用strcmp功能。在你的代码中使用它包括string.h

2

您需要使用特殊功能比较字符串(如ctrcmp

if (strcmp(password, "test") == 0) /* when strings are equal, result is 0 */ 
{ 
... 
} 
else 
{ 
... 
}