I'm trying to make a simple user and password autentication in C. I was told to never use gets() when getting input and I should use fgets() instead. But I'm not sure of how the fgets() works or why is giving me this input. Here is the code.
#include <stdio.h>
#include <string.h>
int login(char *user, char *passwd){
int enter = 0;
char p[6];
char u[6];
printf("User: ");
fgets(u, sizeof u, stdin);
printf("Pass: ");
fgets(p, sizeof p, stdin);
printf("%s\n", p);
if (strcmp(user, u) == 0 && strcmp(passwd, p) == 0){
enter = 1;
}
return entrar;
}
int main(){
char user[] = "admin";
char passwd[] = "12345";
if (login(user, passwd)){
puts("--ACCESS GRANTED--");
}
else{
puts("--Wrong pass or user--");
}
return 0;
}
Ouput
User: admin
Pass:
--Wrong pass or user--
It doesn't even let me enter the password after I press enter.
well.. you had two problems one as suggested here, you should change the size of u and p to 10, the other is, the
fgets
also fetches the new line\n
that you need to remove before comparing the strings.so the complete answer would be: