我正在制作一个程序,首先会注册用户,然后将他引导到登录屏幕。在注册模块中,名称和密码(仅限数字)从用户输入,然后存储在文件中。然后在登录模块中,提示用户输入其用户名(名称)和密码。输入的名称和密码然后存储在变量中,然后与文件中的数据进行比较,如果相等则登录将成功。但是,即使数据完全相同,我从strcmp得到1。这是代码
我存储数据的结构
struct user_data
{
char name[50]; // Name of the user
unsigned long password;
};
注册代码:
void sign_up( void)
{
scanf("%*c");
FILE* data = fopen("data.txt","w");
if ( data == NULL ){
printf("Unable to open file.");
scanf("%*c");
system("clear");
}
system("clear");
printf("\t\t----------------------------\n"
"\t\t| |\n"
"\t\t| SIGN UP PAGE |\n"
"\t\t| |\n"
"\t\t----------------------------");
printf("\n\nName:");
fgets(new_user.name,sizeof(new_user.name),stdin);
printf("\n\n%s",new_user.name);
printf("\nPassword.");
scanf("%lu",&new_user.password); // Getting pass into the struct
printf("\n\n%lu",new_user.password);
fprintf(data,"%s %lu\n",new_user.name,new_user.password);
system("clear");
printf("\n\nSign up complete. :) ");
printf("\nYou will now be redirected to the login screen.\n\n");
fclose(data);
}
登录代码
void sign_in(void)
{
scanf("%*c");
printf("\t\t----------------------------\n"
"\t\t| |\n"
"\t\t| SIGN IN PAGE |\n"
"\t\t| |\n"
"\t\t----------------------------\n");
printf("\n\nName: ");
fgets(data_ver.name,sizeof(data_ver.name),stdin);
printf("\nPassword: ");
scanf("%lu",&data_ver.password);
FILE* data = fopen("data.txt","r");
char name_ver[50];
unsigned long pass_ver;
fscanf(data,"%s %lu",name_ver,&pass_ver);
int cmp = strcmp(data_ver.name,name_ver);
printf("\n\n%d",cmp);
printf("\n%s\t%s\n",name_ver,data_ver.name);
printf("%lu\t%lu",pass_ver,data_ver.password);
scanf("%*c");
if ( (cmp == 0) && (pass_ver == data_ver.password) )
{
system("clear");
printf("\n\nLog in successfull. Welcome. :)");
}
else
printf("\n\nLog in failed. Try again.");
fclose(data);
}
演示输出
正如你在pic中看到的那样,我的数据准确无误但仍然是strcmp返回1