我是 C 语言编程的新手,需要帮助完成我的小任务。
C程序要求:
- 要求用户在命令行输入中键入用户名和密码。
- 程序应要求用户至少尝试两次输入密码。您的程序应该仅在用户输入两个相同的密码时终止。
- 程序应将用户名和密码对存储到当前目录中名为“user.dat”的文本文件中。
我的代码似乎输出到文件,但我在命令提示符窗口中收到此错误:
free(): double free detected in tcache2 Aborted
我还需要在代码中的某处放置一个循环
密码不匹配返回并提示重新
进入,目前我的程序只是
打印“您的密码不匹配,请重新输入
密码我不知道如何处理
下面是我写的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char username [40];
char pw [35];
char confirmpw [35];
FILE *fptr;
fptr = fopen("user.dat", "w");
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Please Enter Your Username:\n");
fgets(username, sizeof(username), stdin);
fprintf(fptr, "%s", username);
printf("please Enter Your Password:\n");
fgets(pw, sizeof(pw), stdin);
// Confirm password prompt
printf("please Re-Enter to Confirm Your Password\n");
fgets(confirmpw, sizeof(confirmpw), stdin);
if(strcmp(pw, confirmpw) == 0){
fprintf(fptr, "%s", pw);
fclose(fptr);
} else {
printf("Your passwords did not match please re-enter your password \n");
//need some type of loop ?
}
fclose(fptr);
return 0;
}
最佳答案
用 while 循环代替 if 语句来请求新密码,直到确认密码正确。
请注意,您在代码中关闭了文件两次,一次是在 if 语句中,第二次是在 main 的末尾。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char username [40];
char pw [35];
char confirmpw [35];
FILE *fptr;
fptr = fopen("user.dat", "w");
// exiting program
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Please Enter Your Username:\n");
fgets(username, sizeof(username), stdin);
fprintf(fptr, "%s", username);
printf("please Enter Your Password:\n");
fgets(pw, sizeof(pw), stdin);
// Confirm password prompt
printf("please Re-Enter to Confirm Your Password\n");
fgets(confirmpw, sizeof(confirmpw), stdin);
while(strcmp(pw, confirmpw) != 0)
{
printf("Your passwords did not match please re-enter your password \n");
fgets(confirmpw, sizeof(confirmpw), stdin);
}
fprintf(fptr, "%s", pw);
fclose(fptr);
return 0;
}
关于c - 用C写的小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63078986/