c - 用C写的小程序

标签 c

我是 C 语言编程的新手,需要帮助完成我的小任务。

C程序要求:

  1. 要求用户在命令行输入中键入用户名和密码。
  2. 程序应要求用户至少尝试两次输入密码。您的程序应该仅在用户输入两个相同的密码时终止。
  3. 程序应将用户名和密码对存储到当前目录中名为“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/

相关文章:

c - pthread 的堆栈大小如何影响内存使用?

c - 初始化大型双数组时出现问题

c - Newlib 在 ARM 嵌入式系统中首次调用时无法分配堆

c - scanf() 将换行符保留在缓冲区中

c - 我是线程和信号量的新手,我似乎可以理解为什么我的代码无法正常工作,我们将不胜感激

c - if (!msize) 是什么意思?

c - 在右值端使用 NULL 指针解引用是否危险?

c++ - 理解 C++ 中的 "Bitwise-And (&)"和 "Unary complement(~)"

c - 清零内存

c - 在套接字中运行服务器代码时如何打印客户端地址