【发布时间】:2022-01-24 18:56:15
【问题描述】:
以下函数用于登录系统。它可以 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;
}
}
}
【问题讨论】:
-
username == fileContents1- 这比较两个指针,而不是指向缓冲区中的内容。 -- 改为使用strcmp函数。 -
谢谢你,虽然该功能的“写入文件”部分仍然不起作用。
-
请参阅fgets() doesn't work after scanf。在第一个
fgets()之后,这个while ((c = getchar()) != '\n' && c != EOF);可能会浪费 following 输入行,因为这里的换行符可能已经被读取。请熟悉各种输入函数如何处理包括换行符在内的空格。最好不要在同一代码中混用不同的输入函数。 -
救命!非常感谢!
标签: c file-handling read-write