Search code examples
ccsvscanf

Using fscanf to read comma delimited doubles


How would I read comma delimited doubles with no white space?

I tried the following:fscanf(file, "%lf[^,], &x) but it doesn't work.

The file will be in the following format:

1.0,2.0,4.0
3.0,6.0,1.0

Solution

  • Instead of using [^,] regular expression you directly use , .

    #include <stdio.h>  
    int main(){  
    FILE *fp;  
    double buff[255];
    int i=0;
    fp = fopen("file.txt", "r");  
    while(fscanf(fp, "%lf,",&buff[i++])!=EOF){  
    printf("%0.1lf ", buff[i-1] );  
    }  
    fclose(fp);  
    }