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",¤t);
}
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);
}
解决方案
首先,您正在username
与自己进行比较。显然,这将永远是一个“真实”的结果。†
您应该将文件中的用户名读入一个变量,然后用户输入另一个变量,然后比较这两个不同的变量。
其次,您需要了解如何正确比较字符数组。
†有时这不是真的,比如比较NaN值,但这不是其中之一!
推荐阅读
- javascript - 如何通过保存以前的值将对象呈现为 HTML?
- javascript - K6 负载测试 - 从单独的文件添加到趋势
- javascript - 为什么将 n 附加到数字(以创建 BigInt)会导致错误?
- r - 使用 For 循环 R 基于其他数据框的单元格创建新数据框
- java - 从表中删除子实体也会删除其表中的父实体
- java - 仅使用 reduce 和 lambda 来解释 Java Stream map 函数
- apache-spark - 从执行任务中停止整个 Spark 作业?
- python - 为什么在指定 Dsize 与 fx/fy 时 OpenCV Resize 会给出不同的像素值?
- laravel - Laravel Livewire 发出事件未触发
- c++ - 有没有办法让我在 C++ 游戏中保持恒定的速度?