【问题标题】:Variables being changed when using the fscanf() in c [duplicate]在 c 中使用 fscanf() 时正在更改的变量 [重复]
【发布时间】:2018-09-23 07:33:18
【问题描述】:

我正在尝试编写一个简单的用户名/密码验证系统。目前我的用户名可以正常工作并正确比较字符串,但我发现我的变量“密码”正在更改。假设用户名是“James”,密码是“123456”,用户名工作正常并且比较正确,但密码正确传递给方法,但是在while (fscanf(file, "%s %s\n", file_username, file_password) > 0) 行上,“password”变量突然更改为“James”,并且然后将其与文件变量 file_password 进行比较。

bool authenticate_login(char *username, char *password)
{
    printf("\nMade it to authentication_login\n");

    FILE *file;
    char *file_username;
    char *file_password;
    bool match;
    printf("\n%s\n", username);
    printf("\nThe password is coming in as: %s\n", password);

    if ((file = fopen("Authentication.txt", "r")) == NULL) {
        perror("fopen");
        return false;
    }

    while (fgetc(file) != '\n'); /* Move past the column titles in the file. */

    /* Each line in the file contains the username and password separated by a white space. */
    while (fscanf(file, "%s %s\n", file_username, file_password) > 0) {
        printf("\n TESTING THIS LINE: %s", password);

        /* Check if the username matches one in the file, and if the password matches for that username. */
        printf("\n\n%s",file_username);
        printf("\n%d",strcmp(file_username, username));
        printf("\n\n%s",file_password);
        printf("\n%s", password);
        printf("\n%d",strcmp(file_password, password));

        if (strcmp(file_username, username) == 0 && strcmp(file_password, password) == 0) {
            match = true;
            break;
        }
    }

    fclose(file);
    return match;
}

【问题讨论】:

  • 未定义行为,因为您没有为file_passwordfile_username 分配内存。

标签: c pointers char scanf


【解决方案1】:

您不应该对file_usernamefile_password 使用指针,而应该使用char 数组。

#define MAX_USERNAME 20
#define MAX_PASSWORD 80

char file_username[MAX_USERNAME];
char file_password[MAX_PASSWORD];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多