fscanf似乎没有阅读价值观。知道为什么吗?输入文件是poly.dat,它有几行对应(x,y)对;见下文。我检查fscanf的输出值,但我不记得是否有更好的方法。任何帮助,将不胜感激。谢谢!
poly.dat:
2
0.0 0.0
1.0 0.0
0.75 0.4330127018922193
0.25 0.4330127018922193
0.0 0.0
0.25 0.4330127018922193
0.75 0.4330127018922193
0.5 0.8660254037844386
0.25 0.4330127018922193
调用:
%。/ program poly.dat poly-converted.dat
源代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3 ) {
printf("usage: %s <input> <output>\n",
argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
FILE *fo = fopen(argv[2], "w");
int N = 0; /* How many tiers? */
double x=0.0, y=0.0;
const double MARGIN = 0.10;
fscanf(fp, "%d", &N);
fprintf(fo, "%d\n", N);
while ( fscanf(fp, "%f %f", &x, &y) == 2) {
double xprime = x + MARGIN;
double yprime = MARGIN + 1.0 - y;
fprintf(fo, "%f %f\n", xprime, yprime);
}
fclose(fp);
fclose(fo);
return 0;
}
答案 0 :(得分:2)
当您使用指向fscanf
的指针致电double
时,您需要使用%lf
代替%f
。否则,您的x
和y
变量会导致错误的结果。
答案 1 :(得分:1)
不要使用fscanf;当它失败时,很难知道消耗了多少输入。
fgets和sscanf可以实现更加可调试的关注点分离。