我知道有人问过类似的问题,但似乎没有一个能解决我的问题。我在运行代码时遇到 Segmentation fault (core dumped)
。
“data.dat”中的第一行是文件中点的总数,接下来的几行是点坐标(二维)。我使用 fgets
读取第一行,然后使用 fscanf
读取下一行。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
FILE *fp;
fp = fopen("data.dat","r");
if (fp == NULL) {
perror("Error");
}
int number;
char str[3];
fgets(str, 3, fp);
number = atoi(str); // number of points to read from the file
printf("number of lines: %d\n", number);
// defining matrix to hold points
float *P = (float *) malloc(sizeof(float)*2*number);
int i = 0;
while(i < number){
int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
printf("%f %f", P[i*number + 1], P[i*number + 2]);
if (ret == 2){
i++;
}
}
fclose(fp);
return 0;
}
编译它没有给我任何错误,但它确实给了我以下警告:
polynom.c: In function ‘main’:
polynom.c:32:24: warning: format ‘%f’ expects argument of type ‘float*’,but argument 3 has type ‘double’ [-Wformat=]
int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
^
polynom.c:32:24: warning: format ‘%f’ expects argument of type ‘float *’, but argument 4 has type ‘double’ [-Wformat=]
我不太明白,因为我确实将参数 3 定义为 float 。
我使用命令行变量运行代码,因此不会出现段错误。
最佳答案
应该是
while (2 == fscanf(fp, "%f%f", &P[i], &P[i+1]) {
i += 2;
if (i >= number*2)
break;
}
关于c - 使用 fscanf 读取 C 中的坐标时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403869/