我正在尝试做这里所做的事情使用C程序从txt文件中读取坐标.我尝试输入的数据采用以下格式:
f 10 20 21
f 8 15 11
. . . .
f 11 12 25
Run Code Online (Sandbox Code Playgroud)
我的点结构的唯一区别是我有一个额外的字符来存储第一列中的字母(可能是也可能不是字母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;
}
Run Code Online (Sandbox Code Playgroud)
因为那里只有一个字符,所以不是字符串只需在代码中使用一个字符:
char t;
}Point;
Run Code Online (Sandbox Code Playgroud)
然后,当你阅读它:
while(fscanf(fp, "%c %f %f %f ", &points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{
Run Code Online (Sandbox Code Playgroud)
我会注意到,在一个结构的末尾有一个1个字符的数组,为你设置结构黑客,这可能不是你的意图...一个很好的理由只使用char t而不是char t[1]
这一行:
for (n=0; n<=i; n++){
Run Code Online (Sandbox Code Playgroud)
应该
for (n=0; n<i; n++){
Run Code Online (Sandbox Code Playgroud)
最后一个注意事项......如果你想要在底部的印刷品中打印出来的字符,你应该使用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 ); }
Run Code Online (Sandbox Code Playgroud)