Calculate the number of characters of the largest word in a file

Asked

Viewed 157 times

1

The file is written as follows:

palavra0palavra0palavra0

Since the words are different. The problem is to calculate the size of the largest word that appears between the zeroes, and the file can have any size.

I’ve been locked into the problem for days. I thought I’d calculate the amount of characters and put them in a string to then compare. The problem is being just compare the size of the words between the zeros to print the largest.

#include <stdio.h>

int main(void) {
 
  char str[64];
  
  scanf("%64s", str);
 
  FILE *f= fopen(str, "r");

  if(!f){
    fprintf(stderr, "ERRO");
    return 1;
  }
  char c;

  //Calculo do tamanho do arq//
  fseek(f, 0, SEEK_END);
 long val1= ftell(f);
 fseek(f,0,SEEK_SET);//


  
 while((fscanf(f, "%c", &c)) != EOF){
   if(c=='0'){
     long y= ftell(f);
    
     
     printf("%ld", y);
     
   }
 }
}

2 answers

1

Your code, although "works", it is not ideal because you are browsing the file twice, unnecessarily.

If the words are separated by zero, just create a counter for the current word size, and increment until you find a zero. When a zero is found, it means that that word is finished, and then you check if that counter is the largest value found so far. Then you Zera the counter and start counting the next word.

Moreover, it was not clear to me whether after the last word there is always a zero or not (your code fails if there is no zero at the end and the biggest word is the last, see here).

Anyway, you can do it in one loop:

FILE *f = fopen ("scores.txt", "r");
if (!f) {
    fprintf (stderr, "ERRO");
    return 1;
}

// tamanho da palavra atual e o maior tamanho encontrado
int tamanho = 0, maior = -1;
int c;
do {
    c = fgetc(f); // lê um caractere
    if (c == '0' || c == EOF) { // se for zero, ou terminou o arquivo, é porque terminou uma palavra
        if (tamanho > maior) // verifica se é maior
            maior = tamanho;
        tamanho = 0; // reinicia a contagem, para a próxima palavra
    } else { // não é zero nem o final do arquivo, aumenta o contador do tamanho da palavra
        tamanho++;
    }
} while (c != EOF);

printf("%d", maior);

Now not only does it not need to read the file twice, it also works if the last word does not have zero after (see here the difference).

I also removed the first scanf, since the value read (the variable str) was not being used for anything. And I switched fscanf for fgetc, the purpose of which is to read a single character of the stream informed data (see more details here).

0

I figured it out, stay there for whoever:

int
main (void)
{

  char str[64];


  scanf ("%64s", str);

  FILE *f = fopen ("scores.txt", "r");

  if (!f)
    {
      fprintf (stderr, "ERRO");
      return 1;
    }

  char c;
  int n = 0, i = 0, a, b, d;
  while (fscanf (f, "%c", &c) != EOF)
    {
      if (c == '0')
    {
      n++;
    }
    }

  int val[n];
  rewind (f);

  while (fscanf (f, "%c", &c) != EOF)
    {
      if (c == '0')
    {
      b = a;
      long y = ftell (f);
      a = y;
      d = a - b;
      val[i] = d - 1;
      i++;

    }
    }
  int Maior = val[0];
  for (i = 0; i < n; i++){
   if(Maior<val[i]){
   Maior=val[i];}}

   printf("%d", Maior);

    
  

  return 0;

}

Browser other questions tagged

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