Comparing user-typed variable with file variable

5

Within my arquivo.txt file I keep two strings "nome" and "senha" , they stay one below the other.

I need to get the name and password entered by the user and compare it with the name and password I have saved in the .txt file

I made a while , so that enquanto for diferente de EOF , it rotates ... Since I did not find a way to compare the typed variables to those in the file, I called strcpy . I created two more char variables and copied the nome and senha that were typed by the user to string2 and string3 . So that I can then compare nome with string2 and senha with string3 .

But there is always a warning that I can not understand.

warning: format '%s' expects argument of type 'char' *', but argument 3 has type 'char'(*)[100]' 

I understand what is written, but I do not understand what that interferes with the code.

The error you give in the program is as follows: Everything I type, it enters as true, it 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);

}
    
asked by anonymous 12.11.2015 / 19:57

2 answers

4

The condition of your while should be

//while( (fscanf(fp, "%s %s", &nome, &senha)) != EOF ) {
while ((fscanf(fp, "%s%s", nome, senha)) == 2) {

The differences are

  • Using & in Variables
    to use & specifies array address (type char(*)[100] )
    without the & the type is automatically converted to char*

  • Instead of testing if the result is different from EOF , the test to be equal to 2 covers more situations that can be error.

  • The space between the two %s is unnecessary

  • formatting to my liking: -)

12.11.2015 / 20:17
4

The @pmg response eliminates the warning when compiling. But there is a logic error in your code. When reading the files from the file you are overwriting the values that the user reported as usuario and senha . Store what is in the file within string2 and string3 .

    
12.11.2015 / 20:22