1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
excound
  • 15
  • 3
  • 5
    `fgets` will read and append the `\n` character to the string. You need to strip it off before comparison. Also I suggest to use `fgets` for user input instead of `scanf` too – Eugene Sh. Apr 07 '21 at 17:47
  • 2
    Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Apr 07 '21 at 17:48
  • Note; `scanf ("%s",acc1.pass);` will not allow spaces as part of `acc1.pass` nor does it cope with long input. Use `fgets()`. – chux - Reinstate Monica Apr 07 '21 at 17:51

2 Answers2

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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.

Blindy
  • 65,249
  • 10
  • 91
  • 131