How do I compare a string that is part of a txt file and another one typed by the user in C?

Asked

Viewed 42 times

-1

I’m a beginner in programming and I’m learning how to manipulate strings, but I’m still a little confused on some kkkkkk things. Finally, regarding the exercise, we have a txt file containing the following content "maria Joao maria maria maria". The user when typing a name (maria or joão) the program returns an integer with the amount of times this name appears in the file.

Entree: Maria

exit: 3

I couldn’t make much progress on the show, but he’s like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  
int main()
{
  FILE *file;
  char frase [27];
  char palavra [8];

  file = fopen ("arquivo.txt", "r");

    if (file == NULL)
    {
        printf ("Erro na abertura do arquivo");
        exit(0);
        }
    scanf ("%s", &palavra);
    
    while (fgets(frase, 27, file)!= NULL){
        retorno = strcmp (palavra, frase); 
    }
    
    printf ("O número de vezes e %d", retorno);
    fclose (file);


}

So I was thinking of going through the user-typed string, character by character, and comparing if each value of that in the strcmp function returns zero and then trying something.

  • use fscanf() to read from disk so gets the string ready to compare with the typed

1 answer

1

Compare to this version

#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE *file = fopen("arquivo.txt", "r");
    if (file == NULL)
    {   printf("Erro na abertura do arquivo");
        return(-1);
    }
    char palavra[8] = "joao";
    char     frase[80];
    unsigned total     = 0;
    while (fscanf(file, "%s", frase) == 1)
        total += (strcmp(palavra, frase) == 0);
    printf("O número de vezes e %d", total);
    fclose(file);
}

And understand that it can be simpler to use fscanf() to read the file. So already receives one word at a time and can compare directly.

Always test the return of scanf(). It is naive not to do this: in your case for example, if you have not read the word you will look for what?

    unsigned total     = 0;
    while (fscanf(file, "%s", frase) == 1)
        total += (strcmp(palavra, frase) == 0);

A loop like this makes the account you want. Understand that fscanf() will return 1 if you can read a data, and strcmp() will return 0 if the strings are equal. Compare with your original code. What you want is to count how many times fscanf() read the word sought.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.