在C中,strcmp()在应该返回0的时候没有返回0

avwztpqn  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(108)

我在比较用户输入的用户名和密码。被比较的字符串是从文件中读入的。不管出于什么原因,它都是在适当地比较用户名,而不是密码。

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

const int MAX_SIZE = 100;

int main()
{
    FILE *fp;
    char *filename = "userdata.txt";
    char arr[100][MAX_SIZE];
    
    //open for writing
    fp = fopen(filename, "r");
    
    //verify open
    if(fp == NULL)
    {
        printf("%s does not exist", filename);
        return 0;
    }

    int index = 0;

    //read file into array
    while(fgets(arr[index], MAX_SIZE, fp) != NULL) 
    {
        index++;
    }
    
    //username input
    char username[100];
    printf("Username: ");
    scanf("%s", username);

    //password input
    char password[100];
    printf("Password: ");
    scanf("%s", password);
    
    
    int check1 = 0;
    int check2 = 0;
    int x;
    for (int i = 0 ; i<index ; i++)
    {
        char *token = strtok(arr[i], " ");
       
        while (token != NULL)
        {
            x = strcmp(token,username);
            printf("%d\n",x);
            printf("%s %s\n",token,username);
            if(!strcmp(token,username))
            {
                check1 = 1;
            }
            
            token = strtok(NULL, " ");
            x = strcmp(token,username);
            printf("%d\n",x);
            printf("%s %s\n",token,password);
            if(!strcmp(token,username))
            {
                check2 = 1;
            }
            
            token = strtok(NULL, " ");
            
            if(check1&&check2)
            {
                printf("The amount is: %s\n",token);
                return 0;
            }
    
            token = strtok(NULL, " ");
            
            check1=0;
            check2=0;
        }
    }
    printf("Username/Password mismatch!!!\n");
    return 0;
}

控制台输出:

Username: user1
Password: password1
0
user1 user1
-5
password1 password1
1
user2 user1
-5
password2 password1
2
user3 user1
-5
password3 password1
3
user4 user1
-5
password4 password1
4
user5 user1
-5
password5 password1
5
user6 user1
-5
password6 password1
Username/Password mismatch!!!
5sxhfpxr

5sxhfpxr1#

fgets读入一行文本时,它也会读取并存储该行末尾的换行符。
这意味着,当您使用strtok拆分字符串并使用" "作为后缀时,读入的密码包括换行符,而通过scanf读取的用户密码(带有%s说明符)不包括换行符,从而导致不匹配。
您可以通过在指定给strtok的分隔符集中包含换行符来解决这个问题。

char *token = strtok(arr[i], " \n");
...
token = strtok(NULL, " \n");

另外,对strcmp的第二组调用是检查用户名而不是密码。因此,与此相反:

x = strcmp(token,username);
        printf("%d\n",x);
        printf("%s %s\n",token,password);
        if(!strcmp(token,username))

你想要这个:

x = strcmp(token,password);
        printf("%d\n",x);
        printf("%s %s\n",token,password);
        if(!strcmp(token,password))

相关问题