Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a .txt text file in C containing float, separated by space

Tags:

c

text

it looks common and obvious but I've already read txt file in C in the past and here I am really stuck.

I have a txt file of this format

0.00000587898458 0.0014451541000 0.000000000001245
0.00012454712235 0.1245465756945 0.012454712115140

... with 640 columns and 480 lines.

I want to put each number of my txt file in a float with the maximum of precision as it is possible, and in a for loop.

FILE* myfile=NULL;
double myvariable=0.0;
myfile=fopen("myfile.txt","r");

for(i =0, k=0 ; i< height; i++)
    for (j=0 ; j< width ; j++){
fscanf(myfile,"%0.20f",&myvariable);
printf("%0.20f",myvariable);
k++;
}
}
fclose(myfile);

Thank you very much for your help

like image 457
thomsala Avatar asked Aug 22 '11 18:08

thomsala


2 Answers

There are several errors in your program - mismatched braces, undefined variables, etc. The most important, however, and the one most likely to be causing your problem, is that you're not passing a pointer to myvariable in your fscanf() call. You'll want to use &myvariable there, so that fscanf() can fill it in appropriately. You probably don't need the format string to be so complicated, either - "%lf" should work just fine to read a double. In fact, gcc warns me with your format string:

example.c:16: warning: zero width in scanf format
example.c:16: warning: unknown conversion type character ‘.’ in format

And then my output becomes just 0. Try "%lf". Here's a complete working example with your sample input:

#include <stdio.h>

#define HEIGHT 2
#define WIDTH  3

int main(void)
{
  FILE *myfile;
  double myvariable;
  int i;
  int j;

  myfile=fopen("myfile.txt", "r");

  for(i = 0; i < HEIGHT; i++)
  {
    for (j = 0 ; j < WIDTH; j++)
    {
      fscanf(myfile,"%lf",&myvariable);
      printf("%.15f ",myvariable);
    }
    printf("\n");
  }

  fclose(myfile);
}

Example run:

$ ./example 
0.000005878984580 0.001445154100000 0.000000000001245 
0.000124547122350 0.124546575694500 0.012454712115140 
like image 127
Carl Norum Avatar answered Oct 05 '22 01:10

Carl Norum


 fscanf(myfile,"%0.20f",myvariable);

You have to pass a pointer, use &myvariable instead. Fix:

 fscanf(myfile, "%lf", &myvariable);
like image 23
Hans Passant Avatar answered Oct 04 '22 23:10

Hans Passant