Question:
Inside my arquivo.txt
I keep two strings "nome"
and "senha"
, they are one below the other.
I need to get the name and password entered by the user and compare it with the name and password that I have stored in the .txt file
OBS: The information below the EOF, I already tried to make != NULL, but it was in an infinite loop.
I made a while
, so that enquanto for diferente de EOF
, it runs… As I couldn't find a way to compare the typed variables with those in the file, I called strcpy
. I created two more char variables and copied the nome
and senha
that were entered by the user to string2
and string3
. So that then I can compare the nome
with string2
and the senha
with string3
.
But I always get a warning that I can't understand.
warning: format '%s' expects argument of type 'char' *', but argument 3 has type 'char'(*)[100]'
I understand what is written, but I don't understand what this interferes with the code.
The error that the program gives is the following: Everything I type, it enters as true, enters the if and prints Welcome!
FILE *fp;
fp = fopen("arquivo.txt", "r");
if (fp == NULL) {
printf("\nO arquivo não foi aberto!");
exit(0);
}
char nome[100], senha[100], string2[100],string3[100];
printf("\n\tNOME........: ");
scanf("%s", nome);
//Tentei fazer com fgets, mas da erro quando uso no while, então
//resolvi deixar o scanf mesmo
printf("\n\tSENHA........: ");
scanf("%s", senha);
printf("\n");
// printf("\n%s %s", nome, senha); //testar o que foi digitado pelo usuario
printf("\n");
while( (fscanf(fp, "%s %s", &nome, &senha)) != EOF ) {
strcpy(string2, nome);
strcpy(string3, senha);
if ( (strcmp(nome, string2) == 0) && (strcmp(senha, string3) == 0) ) {
printf("\nBem-Vindo!\n");
} else {
printf("\nSeu login ou senha estão errados!");
}
}
}
fclose(fp);
}
Answer:
Your while condition should be
//while( (fscanf(fp, "%s %s", &nome, &senha)) != EOF ) {
while ((fscanf(fp, "%s%s", nome, senha)) == 2) {
The differences are
-
use of
&
in variables
use the&
specifies array address (typechar(*)[100]
)
without the&
the type is automatically converted tochar*
-
instead of testing if the result is different from
EOF
, testing to be equal to 2 covers more situations that could be error. -
the space between the two
%s
is unnecessary -
formatting to my liking 🙂