Strcmp没做比较

时间:2015-11-01 15:59:40

标签: c string strcmp

为什么字符串之间的比较不起作用? 我知道user字符串在它们的末尾没有任何结束,但我仍然认为用户名不被接受。

char user[24];
int userLog = -1;

FILE  *usernames;
usernames = fopen("usernames.cfg", "r");

if (usernames == NULL){
    perror("usernames - err");
    return(-1);
}

while(fgets(user, sizeof(user), usernames) !=NULL){

    strtok(user, "\n");
    printf("%s -- %s\n", user, possibleUsername);

    // First edition of question contained:
    // if((possibleUsername, user) == 0)
    // Still having problems with this version:
    if(strcmp(possibleUsername, user) == 0)
        userLog = 1;
    else 
        userLog = 0;

}

if(userLog == 1) printf("Username accepted:   %s\n", possibleUsername);
else if(userLog == 0) printf("Username doesn't exist in the database.\n");
fclose(usernames);

usernames.cfg:

user
justplayit
etc

2 个答案:

答案 0 :(得分:3)

我想它应该是

if(strcmp(possibleUsername, user) == 0)

因为表达式

(possibleUsername, user) == 0

等于

user == NULL

修改

更改

int userLog = -1;

int userLog = 0;

并删除

else
    userLog = 0;

答案 1 :(得分:1)

试试这个:

int main(int argc, char** argv)
{   
    char user[24];
    int userLog;
    FILE* usernames;
    char* userPtr;

    usernames = fopen("usernames.cfg", "r");
    if (usernames == NULL)
    {
        perror("Usernames config not found or read protected");
        return EXIT_FAILURE;
    }

    while(fgets(user, sizeof(user), usernames) != NULL)
    {
        userPtr = strtok(user, "\n");
        if (userPtr != NULL) 
        {
            printf("Username in file => %s", userPtr);
            if (strcmp(userPtr, "find me") == 0)
            {
                userLog = 1;
                break;
            }
            else
            {
                userLog = 0;
            }
        }
    }

    if (userLog)
    {
        printf("User find me accepted");
    }
    else
    {
        printf("User find me not in database");
    }

    fclose(usernames);

    return EXIT_SUCCESS;
}

它与您编写的程序相同,但我使用从strtok返回的额外指针来检查是否找到任何令牌。比较此标记与"零终止"字符串,就像你的可能的名字应该是,适合我。如果possibleUsername是固定长度的字符数组,建议您使用strncmp并设置要比较的字符串的长度,例如strncmp(userPtr,possibleUsername,length)== 0.如果usernames.cfg文件与\ r \ n一起保存,那么strtok会返回" username \ r"而不是"用户名"。也许你可以调试你的程序并检查用户的缓冲区它有什么内容。希望它有所帮助。