typedef struct char usernameMAX_LENGTH; char passwordMAX_LENGTH; Account; Account accountInfo; FILE file1 = fopenidtxt r; if file1 == NULL printf无法打开文件!n; return
以下是完善后的代码:
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 50
typedef struct {
char username[MAX_LENGTH];
char password[MAX_LENGTH];
} Account;
int main() {
Account accountInfo;
FILE *file1 = fopen("id.txt", "r");
if (file1 == NULL) {
printf("无法打开文件!\n");
return 1;
}
fscanf(file1, "%s", accountInfo.username);
fclose(file1);
FILE *file2 = fopen("password.txt", "r");
if (file2 == NULL) {
printf("无法打开文件!\n");
return 1;
}
fscanf(file2, "%s", accountInfo.password);
fclose(file2);
// 比较账号和密码
char inputUsername[MAX_LENGTH];
char inputPassword[MAX_LENGTH];
printf("请输入账号:");
scanf("%s", inputUsername);
printf("请输入密码:");
scanf("%s", inputPassword);
if (strcmp(inputUsername, accountInfo.username) == 0 && strcmp(inputPassword, accountInfo.password) == 0) {
printf("登录成功!\n");
} else {
printf("账号或密码错误!\n");
}
return 0;
}
在上述代码中,首先定义了一个 Account 结构体来存储账号和密码。然后通过 fopen 和 fscanf 函数从文件中读取账号和密码,分别存储在 accountInfo.username 和 accountInfo.password 中。然后,通过用户输入的方式获取一个账号和密码,并通过 strcmp 函数将其与从文件中读取的账号和密码进行比较,判断是否登录成功。最后,根据比较结果输出相应的提示信息
原文地址: https://www.cveoy.top/t/topic/iNcP 著作权归作者所有。请勿转载和采集!