How to read data from a text file in C

I have the following text file:

ax: 0
ay: -9.8
x: 0
y: 50
vx: 8.66
vy: 6

I want to read only the numerical values ​​that will be used for calculations. Is there a way to ignore strings and just read the values ​​as floating?

Here is what I still have:

FILE *fp; 
FILE *fr;

fr = fopen("input_data", "rt");
fp = fopen("out_file.txt", "w");  

if(fr == NULL) {
    printf("File not found");
}

if(fp == NULL) {
    printf("File not found");
}    

float ax = 0, ay = 0,
      x = 0, y = 0,
      vx = 0, vy = 0,
      time = 0, deltaTime = 0; 

fscanf(fr, "%f %f %f %f %f %f %f %f\n",
       &ax, &ay, &x, &y, &vx, &vy, &time, &deltaTime);

printf("%f %f %f %f %f %f %f %f\n",
       ax, ay, x, y, vx, vy, time, deltaTime); 
+3
source share
2 answers

Use this instead:

fscanf(fr, "ax: %f ay: %f x: %f y: %f vx: %f vy: %f", &ax, &ay, &x, &y, &vx, &vy);
+8
source

Use% s where the lines go.

Code example:

#include <stdio.h>

main()
{
  FILE *fp;
  FILE *fr;
  char junk[100];

  fr = fopen("/tmp/x.txt", "rt");

  if(fr == NULL){ printf("File not found");}

  float ax = 0, ay = 0, x = 0, y = 0, vx = 0, vy = 0, time = 0, deltaTime = 0;

  fscanf(fr, "%s %f %s %f %s %f %s %f %s %f %s %f\n", junk, &ax, junk, &ay, junk, &x, junk, &y, junk, &vx, junk, &vy);

  printf("%f %f %f %f %f %f\n", ax, ay, x, y, vx, vy);

}
+1
source

All Articles