C 为什么我能';t比较文件中的数组和我创建登录系统时读取的数组?
C 为什么我能';t比较文件中的数组和我创建登录系统时读取的数组?,c,string,newline,fgets,C,String,Newline,Fgets,strcmp()功能不工作。我从控制台读取的用户名与文件中的用户名不匹配。因此,输出的id是错误的。 解决办法是什么 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { FILE *pass; char str[100],str2[100]; cha
strcmp()
功能不工作。我从控制台读取的用户名与文件中的用户名不匹配。因此,输出的id是错误的。
解决办法是什么
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *pass;
char str[100],str2[100];
char id[100],pw[100];
pass=fopen("password.txt","r");
printf("ENTER USER NAME AND PASSWORD:\n");
printf("USERNAME: ");
gets(id);
printf("\nPASSWORD: ");
gets(pw);
while(fgets(str,100,pass)!=NULL);
{
fgets(str2,100,pass);
if(strcmp(id,str)==0)
{
if(strcmp(pw,str2)==0)
{
printf("ACCEPTED\n");
}
else
{
printf("wrong password");
}
}
else
{
printf("wrong id");
}
}
fclose(pass);
}
#包括
#包括
#包括
int main()
{
档案*通行证;
char-str[100],str2[100];
字符id[100],pw[100];
pass=fopen(“password.txt”、“r”);
printf(“输入用户名和密码:\n”);
printf(“用户名:”);
获取(id);
printf(“\n密码:”);
获取(pw);
while(fgets(str,100,pass)!=NULL);
{
fgets(STR2100,通过);
if(strcmp(id,str)==0)
{
如果(strcmp(pw,str2)==0)
{
printf(“已接受的”);
}
其他的
{
printf(“错误密码”);
}
}
其他的
{
printf(“错误id”);
}
}
fclose(pass);
}
首先,始终使用
也就是说,fgets()
,读取尾随的换行符并将其存储到目标缓冲区中
来自C11
,第7.21.7.2章
fgets
函数从stream指向的流到s指向的数组中读取的字符数最多比n指定的字符数少一个。在新行字符(保留)之后或文件结尾之后,不会读取其他字符。在读取到数组中的最后一个字符之后立即写入空字符
在使用扫描的值之前,应该先去掉该换行符 在访问程序试图打开的文件之前,应检查
fopen()
是否成功
fopen()
在出错时返回NULL
。所以做些类似的事情
pass=fopen("password.txt","r");
if( pass==NULL )
{
perror("Unable to open input file.");
}
else
{
// Use the file
}
char flag=0;
while(fgets(str, sizeof str, pass)!=NULL && fgets(str2, sizeof str2, pass)!=NULL)
{
str[ strlen(str)-1 ] = '\0';
str2[ strlen(str2)-1 ] = '\0';
if( strcmp(str, id)==0 )
{
flag=1;
if( strcmp(str2, pw)==0 )
{
printf("ACCEPTED\n");
}
else
{
printf("wrong password.");
}
break;
}
}
if(flag==0)
{
printf("Wrong id.");
}
而且gets()
已知存在严重的安全问题。看
建议使用fgets()
代替stdin
作为参数。所以不是
gets(id);
试一试
还将检查fgets()
返回的值,以查看fgets()
是否成功。出错时返回NULL
应该注意的是,fgets()
也会从stdin读取尾部的\n
您可以使用类似于strlen()
的函数删除此额外的\n
。请参阅有关删除额外换行符的讨论
在读入pw
时也使用相同的代码
假设您的输入文件在一行中有id,在其后的一行中有相应的密码,您可以执行以下操作
pass=fopen("password.txt","r");
if( pass==NULL )
{
perror("Unable to open input file.");
}
else
{
// Use the file
}
char flag=0;
while(fgets(str, sizeof str, pass)!=NULL && fgets(str2, sizeof str2, pass)!=NULL)
{
str[ strlen(str)-1 ] = '\0';
str2[ strlen(str2)-1 ] = '\0';
if( strcmp(str, id)==0 )
{
flag=1;
if( strcmp(str2, pw)==0 )
{
printf("ACCEPTED\n");
}
else
{
printf("wrong password.");
}
break;
}
}
if(flag==0)
{
printf("Wrong id.");
}
一次读取两行,并在循环的每次迭代之前检查两行是否都成功,以确保读取了正确的值
一旦发现密码错误,您可能希望打破循环
您还可以使用标志变量查看输入的id是否有效,并在最后打印相应的消息。我建议您阅读更多信息,了解它与gets的区别,例如
gets
。顺便说一句,如果您使用fgets
从stdin
读取输入,那么它也会起作用。我无法理解这件事以及如何解决它。或者,如果使用fgets
从stdin
读取输入,则什么也不做。:)@有些编程人员说的没错,但我希望在使用输入之前对其进行消毒。:)