Search code examples
cscanfstdio

Scanning from file two floats with hyphen between


I am trying to scan from a .txt file with two floats with an hyphen in between them. The code works if the hyphen is removed, but I am doing a job for school purposes and the hyphen is needed.

The function is supposed to load the info from the file to an array.

Here is the code:

#include <stdio.h>
#include <estruturas.h>
#include <funcoes.h>

void loadmedicos(medico *pmedico,int total){

    FILE *f;
    medico x; //medico is a typedefined struct with 2 floats
    f=fopen("medicos.txt","rt");

    if(f==NULL){
        printf("Ocorreu um erro ao abrir 'medicos.txt'!\n\n");
    }
    for(int i=0;i<total;i++){
        fscanf(f,"%f",&x.horarioentrada);
        fscanf(f,"%f",&x.horariosaida);
        *(pmedico+i)=x;
    }

    fclose(f);
}

If the .txt contains:

19.30 20.30

Then it will read correctly and output those numbers. If the file contains:

19.30-20.30

The second number won't be read. Why is that and how can I fix it?


Solution

  • You need to include the "-" character as part of the scanf format. That way, the character is skipped over:

    fscanf(f, "%f-%f", &x.horarioentrada, &x.horariosaida);