繁体   English   中英

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

[英]Why am I not getting proper output in the C program?

我编写了一个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);
}

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

学习使用调试器。 您会注意到,进入case 2时,只有在case 1创建的最后一个auth记录在store徘徊。 您还会注意到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.

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM