简体   繁体   English

即使两个字符串相等,strcmp() 也不返回 0

[英]strcmp() doesnt return 0 even both strings are equal

im new into programming and one of my assignments is to build a login system in c, where the username and the password are stored inside a.txt file, the.txt file looks like this我是编程新手,我的任务之一是在 c 中构建一个登录系统,其中用户名和密码存储在 .txt 文件中,.txt 文件如下所示

danielR丹尼尔

77bd 77 天

(top is the username and below is the password) (上面是用户名,下面是密码)

the problem is when I compare the two strings from user input and from the.txt file of both username and password using strcmp(), it doesnt return to 0 even tho both strings are equal问题是当我使用 strcmp() 比较用户输入和用户名和密码的 .txt 文件中的两个字符串时,即使两个字符串相等,它也不会返回 0

#include <stdio.h)
#include <conio.h>
#include <string.h>
#include <stdlib.h>

struct login 
{
char name[25];
char pass[25];
};
void login()
{
struct login acc1,acc2;
printf("input your username : ");
scanf ("%s",acc1.name);
printf("input your password : ");
scanf ("%s",acc1.pass);
FILE* fp = fopen("account.txt","r");
fgets(acc2.name,25,fp);
fgets(acc2.pass,25,fp);
if (strcmp(acc1.name,acc2.name)==0 && strcmp(acc1.pass,acc2.pass)==0)
{
printf("login successful\n");
}
else
{
printf("wrong password or username");
}

I've even tried using printf to match the usernames and passwords from userinput and from.txt files and they all are equal.我什至尝试使用 printf 来匹配来自 userinput 和 from.txt 文件的用户名和密码,它们都是相等的。 I wonder why strcmp() doesnt return to 0. any help?我想知道为什么 strcmp() 不返回 0。有什么帮助吗?

The function fgets can append the input string with the new line character '\n' provided that the destination array has enough space.如果目标数组有足够的空间,function fgets可以 append 输入字符串与换行符'\n'

You need to remove it.您需要将其删除。

You can do it for example the following way例如,您可以通过以下方式执行此操作

acc2.name[ strcspn( acc2.name, "\n" ) ] = '\0';
acc2.pass[ strcspn( acc2.pass, "\n" ) ] = '\0';

after these calls在这些电话之后

fgets(acc2.name,25,fp);
fgets(acc2.pass,25,fp);

Pay attention to that it will be more safer to initialize data members at least of the object acc1 .请注意,至少初始化 object acc1的数据成员会更安全。

For example例如

struct login acc1 = { .name = "", .pass = "" };
struct login acc2;

and you should check that the file was opened successfully and calls of fgets also were successful.并且您应该检查文件是否已成功打开并且fgets的调用也是否成功。

Read the documentation on fgets , it considers new lines valid characters and stores them in your string buffer.阅读有关fgets的文档,它认为新行是有效字符并将它们存储在您的字符串缓冲区中。 Reduce the length of your string by one to offset it.将字符串的长度减一以抵消它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM