[英]Username not written when saving username and password to a file
以下 function 用于登录系统。 它可以 100% 工作,除了变量“用户名”(用户输入)不写任何内容/空白(数据丢失),而变量“密码”完美地写入数据。
void login()
{
while (1)
{
printf("Enter a selection (number 1 or 2), then press enter.\n\n");
printf("1. Login\n2. Register\n\n");
int selection = 0;
scanf("%d", &selection);
if (selection == 1)
{
FILE *fp;
char username[24] = {'\0'};
printf("\nEnter username:\n");
fgets(username, sizeof(username), stdin);
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
char password[24] = {'\0'};
printf("\nEnter password:\n");
fgets(password, sizeof(password), stdin);
char extension[4] = ".txt";
char fileName[strlen(username) + strlen(extension) + 1];
strcpy(fileName, username);
strcat(fileName, extension);
fp = fopen(fileName, "r");
if (fp != NULL)
{
char fileContents1[24] = {'\0'};
char fileContents2[24] = {'\0'};
for (int i = 0; i <= 1; i++)
{
if (i == 0)
{
fgets(fileContents1, sizeof(fileContents1), fp);
if (i == 1)
{
fgets(fileContents2, sizeof(fileContents2), fp);
}
}
if ((username == fileContents1) && (password == fileContents2))
{
menu();
} else
{
printf("\nInvalid username or password, try again.\n\n");
continue;
}
}
} else
{
printf("\nError, try again.\n\n");
continue;
}
fclose(fp);
} else if (selection == 2)
{
FILE *fp;
char username[24] = {'\0'};
printf("\nChoose a username:\n");
fgets(username, sizeof(username), stdin);
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
char password[24] = {'\0'};
printf("\nChoose a password:\n");
fgets(password, sizeof(password), stdin);
char extension[4] = ".txt";
char fileName[strlen(username) + strlen(extension) + 1];
strcpy(fileName, username);
strcat(fileName, extension);
fp = fopen(fileName, "w");
if (fp != NULL)
{
fputs(username, fp);
fputs(password, fp);
printf("\nLogin created successfully.\n\n");
} else
{
printf("\nError, try again.\n\n");
continue;
}
fclose(fp);
} else
{
printf("\nInvalid selection, try again.\n\n");
continue;
}
}
}
至少有这些问题:
剩下的'\n'
scanf("%d", &selection);
在数字之后不消耗任何东西,比如尾随'\n'
。
fgets()
读取'\n'
- 很短的一行。
scanf("%d", &selection);
...
fgets(username, sizeof(username), stdin);
最好不要将scanf()
与fgets(...,..., stdin)
混合使用。
最好只使用fgets()
。
记住fgets()
读取并保存最终'\n'
您可能希望在fgets()
之后删除潜在'\n'
。
username[strcspn(username, "\n")] = '\0';
指针比较
username == fileContents1
比较两个字符串的地址。 要比较字符串的内容,请使用strcmp()
。
可疑代码
int c = 0; while ((c = getchar());= '\n' && c != EOF);
只有在fgets()
未能读取整行时, fgets()
才有意义。 如果fgets()
这样做了,那么这个while()
会读取并抛出下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.