#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
clrscr();
char username[15], password[15], ch, usr[15], pass[15];
int choice, i=0, found=0;
printf("1.Add Admin");
printf("\n2.Log-in Admin");
printf("\n3.Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: FILE *acc;
if((acc = fopen("c:\\account.txt","a+")) == NULL)
printf("FILE NOT FOUND!");
else
{
do
{
fscanf(acc,"%s %s%",username, password);
}while(!feof(acc));
}
printf("\nEnter desired username: ");
scanf("%s",username);
printf("Enter desired password: ");
while(ch != 13)
{
ch = getch();
password[i] = ch;
i++;
printf("*");
}
password[i]='\0';
fprintf(acc,"%s %s\n",username,password);
fclose(acc);break;
case 2: FILE *log;
log = fopen("c:\\account.txt","r");
printf("Username: "); //user input username and password//
scanf("%s",usr);
printf("Password: ");
while(ch != 13)
{
ch = getch();
pass[i] = ch;
i++;
printf("*");
}
pass[i]='\0';
while(!feof(log)&& found == 0)
{
fscanf(log,"%s %s",username,password); //this is where i am having some problem//
if(strcmp(usr,username) == 0 && strcmp(pass,password));
found = 1;
if(found == 1)
printf("\nWelcome!");
else
printf("\nInvalid username or password");
}
fclose(log);
}
getch();
return(0);
}
我无法进行验证工作,即使用户名和密码错误,也总是表示欢迎。 如何将用户输入字符串与文件内的数据进行比较? 不幸的是,turbo c是必需的。
答案 0 :(得分:0)
if(strcmp(usr,username) == 0 && strcmp(pass,password));
在密码的strcmp
处,检查是否已返回0
。试试这个
if(strcmp(usr,username) == 0 && strcmp(pass,password) == 0)
并且,您的if
循环最后有一个;
,这意味着found = 1
不在if
循环内,删除了;
< / p>
答案 1 :(得分:0)
当前密码输入包括密码中的换行符,当通过fscanf检索密码时,省略换行符。
为两个密码输入尝试此密码输入
printf("Enter desired password: ");
i = 0; // to be safe set i to zero
while( ( ch = getch()) != '\n') // newline will be detected here and not added to password
{
password[i] = ch;
i++;
printf("*");
if ( i >= 14) { // to prevent a long password overwriting the array
break;
}
}
password[i]='\0';
编辑:
&#39; \ n&#39;在linux和gcc上为我工作得很好。使用turbo c时,您可能需要使用而不是&#39; \ n&#39; 13,你必须开始,或者可能&#39; \ r&#39;
如果文件中有多组用户/密码,您将看到每个集的欢迎/无效消息,因为该消息位于从文件读取的while循环内。
尝试此操作从文件中读取并验证用户/密码
found = 0;
while( ( fscanf(log," %s %s",username,password == 2) {
{
if(strcmp(usr,username) == 0 && strcmp(pass,password) == 0)
{
found = 1;
break;
}
}
if(found == 1) // moved outside while loop so it is seen only once
printf("\nWelcome!");
else
printf("\nInvalid username or password");