簡體   English   中英

從C格式的ASCII格式文件中解析數據

[英]Parsing data from ASCII formatted file in C

我正在嘗試做這里所做的事情使用C程序從txt文件中讀取坐標 我嘗試輸入的數據采用以下格式:

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;
}Point;

然后,當你閱讀它:

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

我會注意到,在一個結構的末尾有一個1個字符的數組,為你設置結構hack ,這可能不是你的意圖......使用char t而不是char t[1]一個很好的理由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 ); }

檢查一下

  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<i

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM