Calculate the time a car was parked

Asked

Viewed 152 times

5

I’m reading a file parque.txt which contains the time a car has been in a car park of the type "9h00 10h30", this in each line.

I was trying to get those hours on every block of char, in this case would have hora_i="9", min_i="00", hora_f="10", min_f="30", the problem is that in printf final it shows hora_i="9", min_i="009", hora_f="10009", min_f="3010009".

I’ve tried doing it fflush(stdin), but it didn’t work...

void calcula_estacionamento()
{
    FILE *f;
    int n=0,i=0;
    char linha[MAX],hora_i[2]="",min_i[2]="",hora_f[2]="",min_f[2]="";
    f=fopen("parque.txt","r");
    while(fgets(linha,MAX,f)!=NULL)
    {
        while(linha[n]!='h')
        {
            hora_i[i]=linha[n];
            n++;
            i++;
        }
        i=0;
        n++;
        while(linha[n]!=' ')
        {
            min_i[i]=linha[n];
            n++;
            i++;
        }
        i=0;
        n++;
        while(linha[n]!='h')
        {
            hora_f[i]=linha[n];
            n++;
            i++;
        }
        i=0;
        n++;
        while(linha[n]!='\0')
        {
            min_f[i]=linha[n];
            n++;
            i++;
        }
        printf("\n%s %s %s %s",hora_i,min_i,hora_f,min_f);
        n=0;
        i=0;
    }
}

1 answer

5


The null characters (\0) in each of its strings. That is, each of its vectors must have up to 3 characters:

char linha[MAX], hora_i[3] = "", min_i[3] = "", hora_f[3] = "", min_f[3] = "";

It is important that you finish all the string correctly while reading your code

hora_i[i] = '\0';
i=0;
// ...
min_i[i] = '\0';
i=0;
// ...
hora_f[i]= '\0';
i=0;
// ...
min_f[i]= '\0';

Finally, if you are actually going to read multiple lines from a file, it is important to predict both the end of the file and the end of a line:

while(linha[n]!='\0' && linha[n]!='\n') 
{ 
    // ...

Functional example in Ideone


Important points that I could not include in the example

Failed error handling when opening the file:

f=fopen("parque.txt","r");
if(f == NULL) {
    perror("Erro abrindo o arquivo");
    return(-1);
}

As well as the treatment to close it:

fclose(f);
  • thanks, now solved the error, I didn’t remember that detail of ' 0' to finalize the string... I when I just read files I don’t usually do fclose(), I don’t know if it’s good policy, but I do so

  • No problem, Miguel, I’m glad I could help. About files (and pointers in general), my tip is: whenever allocate something already type the code to close :). If the answer solved your problem don’t forget to accept it.

Browser other questions tagged

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