我正在尝试做这里已经完成的事情 Read co-ordinates from a txt files using C Program .我尝试输入的数据采用以下格式:
f 10 20 21
f 8 15 11
. . . .
f 11 12 25
我的点结构的唯一区别是我有一个额外的字符来存储第一列中的字母(可能是也可能不是字母 f)。我想我要么声明了我的 char 错误,要么我在 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;
}
最佳答案
因为那里只有 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 ); }
关于c - 从 C 语言的 ASCII 格式文件中解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14729035/