fscanf question & further puzzle

Kent Black,L08,640,7754072 kab at reed.bitnet
Fri Dec 29 10:07:24 AEST 1989


I dislike [fs]?scanf, and rarely use any of them, but bear with me for
NEW and IMPROVED adventures of format troubles.

In article <6983 at ohstpy.mps.ohio-state.edu> SMITHJ at ohstpy.mps.ohio-state.edu writes:
>
>	stream = fopen("try2.gbk","r");
>	fscanf(stream,"%-30s %-30s",instr1,instr2);
>	fclose(stream);
>
>/* Jeffery G. Smith, BS-RHIT (AKA Doc. Insomnia, WMHD-FM)       *

As has already been pointed out, fscanf does not recognize `-'.
Fscanf separates input by whitespace before field width, so even when
you specify the field width you get only the first "word" of input
into each variable:  e.g., the code
	...
        fscanf(stream,"%3s%30s",instr1,instr2);
        printf("'%s':'%s'\n", instr1, instr2);
	...
yeilds
	$ a.out
	'Try':'ing'

However, the manual says you can specify an alternate "scanset" with
brackets.  This might be useful if you know the data is formatted with
strict columns (not something I would want to depend upon, but by way of
example, besides which, Mr. Smith's code is so formatted).  So it seems
we could use:
	...
        fscanf(stream,"%30[ a-zA-Z]s%30[ a-zA-Z]s",instr1,instr2);
        printf("'%s':'%s'\n", instr1, instr2);
	...
But this yeilds
	$ a.out
	'Trying                        ':''
	
The first field is what I expected, the second is always empty (the
input file consists of the single line inside the quotes:
"Trying                        Hoping                        ")
I read the manual and tried several variations, including making the
first format only 3 char's long as with the first example, letting the
second format be simply '%s', making certain the arrays were large
enough to hold the entire string and the trailing NULL, and other
obvious things.  Same behaviour on Ultrix and 4.3BSD.

I haven't any more time to waste at the moment but if nobody can help
I will end up running over the source for a function I never use. 
;-(
And then I will bother you all again by posting what I discover.
;-)

any illumination appreciated,
-- kab



More information about the Comp.lang.c mailing list