[GNHLUG] Silly C/C++ question...
Ric Werme
ewerme at comcast.net
Mon Dec 1 20:35:01 EST 2008
> I am sure I will kick myself when I find out the answer, but...
>
> I have a text file that for now consists of 3 lines, later it will have
> data.
> line 1: integer representing the array size
> line 2: four doubles separated by commas
> line 3: \n
>
> Here is the code fragment that I have been trying to get to work. I have
> no idea why I am getting the output I am.
Here are the juicy lines:
> fscanf(fp, "%i", &N); // Find file length ==> read first line
1) Use printf control strings. "%d\n" might work.
2) You're looking at your file as a bunch of lines. (You probably edit
with vi.) A Unix file is a bag o' bytes. Be sure to have fscanf read
and discard the \n. May not be necessary, actually. If you're expecting
a bunch of lines, you should read the file a line at a time and parse
that.
> fscanf(fp, "%d%d%d%d", &fstart1, &fend1, &M1, &dt1); // get fstart, ...
3) Add commas to step over commas. The number parser will skip white
space.
4) It's a very good idea to check the return value from scanf. It returns
when it can't parse the data and the item count gives you good clues.
My code:
#include <stdio.h>
main() {
char buf[4097];
int size;
double w, x, y, z;
FILE *fp;
int num;
fp = fopen("foo.bruce", "r");
fgets(buf, sizeof(buf), fp);
num = sscanf(buf, "%d", &size);
printf("%d: size %d\n", num, size);
fgets(buf, sizeof(buf), fp);
num = sscanf(buf, "%lf,%lf,%lf,%lf", &w, &x, &y, &z);
printf("%d: %6.4lf %6.4lg %6.4lf %6.4lf\n", num, w, x, y, z);
fgets(buf, sizeof(buf), fp);
num = sscanf(buf, ""); /* Pointless */
printf("%d: %x\n", num, buf[0]);
}
My data:
666
0, 5e-10,2.7182, 3.14159
My output:
tux:c> ./bruce
1: size 666
4: 0.0000 5e-10 2.7182 3.1416
0: a
More information about the gnhlug-discuss
mailing list