简体   繁体   中英

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

danielR

77bd

(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

#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. I wonder why strcmp() doesnt return to 0. any help?

The function fgets can append the input string with the new line character '\n' provided that the destination array has enough space.

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 .

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.

Read the documentation on fgets , it considers new lines valid characters and stores them in your string buffer. Reduce the length of your string by one to offset it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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