将密码复制到数组中,然后进行压缩



我正试图将密码写入用户键入的文件中,并保存到数组中,这样我就可以比较用户输入的内容,并允许他们登录。这是我的代码,必须是ANSI标准。目前,我无法获得密码进行比较并给出正确的输出。

#include <stdio.h>
#include <stdlib.h>
#define NAMELENGTHS 20
#define TEXTLENGTHS 200
#define PASSWORDS 7
struct patients
{
char forename[NAMELENGTHS];
char lastname[NAMELENGTHS];
int birthDay;
int birthMonth;
int birthYear;
float hight;
float weight;
char conditions[TEXTLENGTHS];
char medication[TEXTLENGTHS];
int vaxno;
char comments[TEXTLENGTHS];
};
void emptyBuffer(void);

int main(void)
{
FILE *fin;
char username[NAMELENGTHS];
char password[PASSWORDS];
char userInput[PASSWORDS];
printf("please enter a username: ");
scanf("%s", username);
emptyBuffer();
if(!(fin = fopen(username, "r")))
{
printf("user not recognisedn");
return 1;
}
while(!feof(fin))
{
fgets(password, PASSWORDS, fin);
}
fclose(fin);
printf("Please enter a password: ");
scanf("%s", userInput);
emptyBuffer();
if(userInput == password)
{
printf("Successful Login");
}
else
{
printf("Login Failed please restart");
return 1;
}
return 0;
}

void emptyBuffer(void)
{
while(getchar() != 'n')
{
;
}
}

您想要追加"。txt";到用户名。您可以使用strcat。另外,使用strcmp来比较字符串。

printf("Enter user name: ");
// The -4 is to leave room for ".txt"
if (fgets(username, sizeof(username) - 4, stdin)) {
// fgets leaves newline. remove it
size_t len = strlen(username);
if (len > 0 && 'n' == username[len - 1]) username[len - 1] = '';
// Now append .txt
strcat(username, ".txt");
// Read the password
if (!(fin = fopen(username, "r"))) {
// Remove ".txt" for error message
username[len - 1] = '';
fprintf(stderr, "user "%s" not recognizedn", username);
return 1;
}
// Read the password from the file
if (fgets(password, sizeof(password), fin)) {
len = strlen(password);
if (len > 0 && 'n' == password[len - 1]) password[len - 1] = '';
printf("Enter password: ");
// Get the password from the user
if (fgets(userInput, sizeof(userInput), stdin)) {
len = strlen(userInput);
if (len > 0 && 'n' == userInput[len - 1]) userInput[len - 1] = '';
// Compare
if (0 == strcmp(userInput, password)) {
puts("Successful Login");
}
else {
fclose(fin);
fputs("Login Failed please restartn", stderr);
return 1;
}
}
}
fclose(fin);
}

最新更新