Reading double-precision floating point numbers from a file?

22,176

Solution 1

double d;
scanf("%lf", &d);

scanf will skip the white space chars and let you read all values in a simple loop. If you are reading from a file then fscanf should be your choice.

scanf documentation and fscanf documentation

Solution 2

You should use fgets AND sscanf and their return values like,

char line[100];
while( fgets( line,100,filepointer ) )
  if( 1==sscanf(line,"%lf",&adoublevariable) )
    printf("%f",adoublevariable);
  else
    puts("not a double variable");
Share:
22,176
primehunter326
Author by

primehunter326

Updated on July 09, 2022

Comments

  • primehunter326
    primehunter326 almost 2 years

    My problem is pretty simple; I have text file filled with double precision floating point numbers which I need to read in and store in a matrix. I know how to open the file but from there I'm not sure how to parse out the data and convert it. The numbers are separated by spaces and newlines and each is preceded by a sign (either '+' or '-'). I'm not sure which function (scanf, fgetc, etc.) I should use to read in the data. I'm not new to programming though this is my first time working extensively with C. Detailed explanations are welcome as I'd like to get more familiar with how tasks like this are handled. Thanks!

    Edit: Should have clarified that the file is generated by code so no need to worry about users messing with it. Also From reading the docs it seems like I could just use fread to load all of the contents of the file into a string and then use atof to parse out each double. Is this correct?