c - 使用 C 验证文件中的登录凭据

标签 c

我的程序应该检查凭据是否存在于创建的“MyDetails.txt”文件中,如果是,则允许用户继续,否则终止。但是,该程序接受传递给它的任何值并重写现有数据。 我想找出代码中存在哪些错误以及是否有其他替代方法可以解决它。(验证文件中的凭据)。 下面是该程序的代码。

#include<stdio.h>
#include<string.h>
#include<conio.h>
#include <stdlib.h>
main()
{
FILE *Credentials;
char username[15];
char password[12];

//open file for writing
Credentials  =fopen("MyDetails.txt","w");
//check if file exists
if(Credentials == NULL)
{
    printf("File does not exist\n");
    return;
}
//New User
printf("Enter Username\n");
scanf("%s",&username);
fprintf(Credentials,"Username:%s\n",username);

printf("Enter Password\n");
scanf("%s",&password);
fprintf(Credentials,"Password:%s\n",password);

    if(username==username)
    {
    if(password=password)
    {
    printf("Login Successfull\n");  

    printf("\n");

    float result;
    int choice,num;
    printf("Press 1 to Exit\n");
    printf("Press 2 to Input Current Reading\n");
    printf("Press 3 to Calculate Bill\n");
    printf("Press 4 to Make Payment\n");
    choice = input();
    float current,rate,previous,units,monthly,bill,stand,paid;
    switch (choice){
    case 1:{
    exit(0);
    break;
    }

    case 2:{
    printf("Input Current Reading\n");
    scanf("%f",&current);

    }

    case 3:{
    printf("Enter Rate\n");
    scanf("%f",&rate);
    printf("Enter Previous Reading\n");
    scanf("%f",&previous);


    units=current-previous;   
    monthly=units*rate;                 
    bill=150+monthly;

    printf("\n Total Bill:%.3f\n",bill);


    }
    case 4:{
    printf ("------PAYMENT------\n");
    printf("\n");
    printf("Amount To Pay is %.3f",bill);
    printf("\n");
    printf("Enter Amount\n");
    scanf("%f",&paid);
    printf("Remaining Balance\n %.3f",bill-paid);
    break;
    }   
    }
    }
    else
    {
    printf("\n Wrong Password");
    }
    }
    else
    {
    printf("\n User Doesn't Exist'");
    }
    return 0;
    }
    int input()
    {
    int number;
    scanf("%d",&number);
    return (number);
    }

    void output(float number)
    {
    printf("%f",number);
    }           

最佳答案

首先,您将用户名与其自身进行比较。显然,这始终是“真实”的结果。

您应该将文件中的用户名读取到一个变量中,然后将用户输入到另一个变量中,并比较这两个不同变量.

其次,你需要了解how to properly compare character arrays .

有时这不是真的,例如比较 NaN 值,但这不是其中之一!

关于c - 使用 C 验证文件中的登录凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972156/

相关文章:

c - 使用 calloc 分配的免费二维数组

谁能向我解释一下到底是什么原因导致了这个段错误以及如何克服这个问题?

c - 为什么循环会这样工作?

c - 如何使用指向结构的指针进行迭代?

c - 通知父线程终止

C:符号 x=y[a=b] 意味着什么?

c++ - 给定一个字符串形式的日期/时间,知道当时是否为 DST 的最佳方法是什么?

c - do-while循环不断重复

c++ - Win32 确定键盘何时连接/断开连接

c - 在纯 C 中构建 Visual Studio 2013 项目