如何从C中的文本文件中读取数据

时间:2011-05-27 22:42:19

标签: c file-io

我有以下文本文件:

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

我想只读取用于计算的数值。有没有办法忽略字符串,只是将值读作浮点数?

这是我到目前为止所做的:

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); 

2 个答案:

答案 0 :(得分:8)

请改用:

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

答案 1 :(得分:1)

使用字符串去的%s。

示例代码:

#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);

}