【问题标题】:Parsing data from ASCII formatted file in C从 C 中的 ASCII 格式文件解析数据
【发布时间】:2013-02-06 12:24:09
【问题描述】:

我正在尝试做这里已经完成的事情 Read co-ordinates from a txt files using C Program 。我尝试输入的数据是这种格式:

f 10 20 21
f 8 15 11
. . .  .
f 11 12 25

我的点结构的唯一区别是我有一个额外的字符来存储第一列中的字母(可能是也可能不是字母 f)。我想我要么声明我的字符错误,要么我在printf 中错误地调用它。无论哪种方式,我只读取第一行,然后我的程序终止。有什么想法吗?

下面是我的 MWE

#define FILEPATHtri "/pathto/grid1DT.txt"
#define FILEPATHorg "/pathto/grid1.txt"
#define MAX  4000

#include <stdio.h>
#include <stdlib.h>
#include "math.h"

typedef struct
{    
    float x;
    float y;
    float z;
    char t[1];
}Point;

int main(void) {

    Point *points = malloc( MAX * sizeof (Point) ) ;

    FILE *fp ;
    fp = fopen( FILEPATHtri,"r");

int i = 0;

while(fscanf(fp, "%s %f %f %f ", points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{
    i++;
}
fclose(fp);

int n;


for (n=0; n<=i; n++){

    printf("%c  %2.5f %2.5f %2.5f \n", points[i].t, points[n].x, points[n].y, points[n].z ); }


    printf("There are i = %i  points in the file \n And I have read n = %i  points ",i,n);

return 0;

}

【问题讨论】:

  • 你为什么使用char t[1]而不是简单的char t
  • 似乎是熟悉调试器的绝佳时机,如果您使用的是基于 linux/unix/etc 的系统,我可以推荐 GDB!
  • @Fredrik : 我推荐 DDD
  • 你应该检查 fp 是否有效。

标签: c parsing matrix


【解决方案1】:

由于那里只有 1 个字符,而不是字符串,只需在代码中使用单个字符:

    char t;
}Point;

那么当你读进去的时候:

while(fscanf(fp, "%c %f %f %f ", &points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{

我会注意到,在结构的末尾有一个包含 1 个字符的数组,为您设置了 struct hack,这可能不是您的意图... 一个很好的理由只使用 char t 代替的char t[1]

还有这一行:

for (n=0; n<=i; n++){

应该是

for (n=0; n<i; n++){

最后一点...如果您想打印出您在底部打印件中读到的字符,您应该使用n

// note your previous code was points[i].t
printf("%c  %f %f %f \n", points[n].t, points[n].x, points[n].y, points[n].z ); }

【讨论】:

    【解决方案2】:

    检查一下

      while(fscanf(fp, "%c %f %f %f ", points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
        {
        i++;
    }
    fclose(fp);
    
    int n;
    
    
    for (n=0; n<i; n++){
    
        printf("%c  %2.5f %2.5f %2.5f \n", points[n].t, points[n].x, points[n].y, points[n].z ); }
    
    
        printf("There are i = %i  points in the file \n And I have read n = %i  points ",i,n);
    getch();
    return 0;
    
    }
    

    修改是因为只有一个字符被读取 %s 修改为 %c 也在 printf 它不是 points[i].t 它的 points[n].t 。此外,for循环中的限制检查也更正为n&lt;i

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多