Home > Net >  read a double number from file - c
read a double number from file - c

Time:10-29

I have file filled with rows of data: each row contains:
'char' space 'double'. e.g:

a 17.322\n
c 9.45\n

I want to 'eat' the \n and the char, and read only the double number. what is the best way to do it.

thanks, and sorry if I have English mistakes

CodePudding user response:

I think simple fscanf can do the job

#include <stdio.h>

int main()
{
    FILE* f = fopen("test", "r");
    float n;

    while(fscanf(f, "%*[a-z]%f ", &n) == 1)
        printf("%f, ", n);

    return 0;
}
  • "%*" ignores everything it reads
  • "[a-z]" reads characters from range 'a' to 'z'
  • "%f" reads a single precision floating point number (in other words float)
  • " " ignores all whitespace characters
  • fscanf returns EOF in case of reading error (ex. end of file) or number of read values which in our case is 1
  •  Tags:  
  • c
  • Related