为什么我在C程序中没有得到正确的输出?

时间:2018-06-30 15:43:09

标签: c

我编写了一个C程序来注册用户并使用相同的用户名和密码登录,但是尝试登录时收到Username invalid/doesn't exist消息。知道我在以下代码中做错了什么吗?另外,当我重新运行该程序时,无法收到Login Successfully消息。即使我在代码中使用了注释的fscanf()函数,也无法得到正确的输出。

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

struct database {
    char name[20];
    char email[30];
    char user[10];
    char pass[20];
} store;

int main() {
    int count, entries, choice;
    char username[10];
    char password[20];
    FILE *fptr;
    fptr = fopen("E:\\login.bin", "ab+");
    printf("Welcome to the user authentication program v1.2 .\n");
 Again:
    printf("\n1. Register\n");
    printf("2. Login\n");
    printf("3. Exit\n");
    printf("\nEnter your choice: ");
    scanf("%d", &choice);
    switch(choice) {
      case 1:
        printf("\nEnter the number of users.\n");
        printf("Users = ");
        scanf("%d", &entries);
        for (count = 1; count <= entries; count++) {
            /*printf("\nEnter your email: ");
            scanf("%s", &store.email);
            fprintf(fptr, "%s\n", store.email);*/

            printf("\nEnter a username: ");
            scanf("%s", &store.user);
            fprintf(fptr, "%s\n", store.user);

            printf("\nEnter a password: ");
            scanf("%s", &store.pass);
            fprintf(fptr, "%s\n", store.pass);

            printf("\nRegistration successful.\n");

        }
        goto Again;
        break;

      case 2:
        printf("Enter your username: ");
        scanf("%s", &username);
        ///fscanf(fptr, "%s", &store.user);
        printf("Enter your password: ");
        scanf("%s", &password);
        ///fscanf(fptr, "%s", &store.pass);
        if (strcmp(username, store.user) == 0) {
            if (strcmp(password, store.pass) == 0) {
                printf("\nLogin Successful.\n");
            } else {
                printf("\nIncorrect password!\n");
            }
        } else {
            printf("\nUsername invalid/doesn't exist.\n");
        }
        break;

      case 3:
        exit(1);
        break;
    }
    fclose(fptr);
}

2 个答案:

答案 0 :(得分:0)

您的程序不完整。您将身份验证数据写入从未读过的文件。在尝试查找匹配项时,您应该考虑构建数据库记录的数组并遍历每个记录。

学习使用调试器。您会注意到,进入case 1时,只有在store中创建的最后一条auth记录在case 2中徘徊。您还会注意到fscanf(fptr, "%s", &store.user)仅读取一条记录。

请考虑以下程序大纲:

if exist authfile LoadAuth()
if user enter new auth data, update internal database, then write to file.
if user attempts login, create a temp record with their auth data and then 
iterate through the database, comparing that record to ones in the database.
  If not found, fail the login.

答案 1 :(得分:0)

您将登录名和密码读入本地结构并将凭据附加到文件中,但是您从未读过文件以检查数据库中的所有登录名/密码。

仅当您注册一个用户并在此之后立即登录时,该程序才有效。此外,您没有错误处理,因此无效输入会在许多地方导致未定义的行为。