Reputation: 607
fscanf doesn't seem to be reading in values. Any idea why? The input file is poly.dat, and it has several rows corresponding to (x, y) pairs; see below. I check the output value of fscanf, but I don't remember if there's a better way. Any help would be appreciated. Thanks!
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
invocation:
% ./program poly.dat poly-converted.dat
source code:
#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;
}
Upvotes: 1
Views: 122
Reputation: 726479
When you call fscanf
with a pointer to double
, you need to use %lf
instead of %f
. Otherwise, you are going to get wrong results in your x
and y
variables.
Upvotes: 2
Reputation: 43487
Don't ever use fscanf; when it fails it is very hard to know how much input has been consumed.
fgets and sscanf make for a much more debuggable separation of concerns.
Upvotes: 1