W
Walter Roberson
Rajen said:I have a problem reading the float values.
I modiifed my above code as:
....
fclose(fp);
fp=NULL;
fp = fopen("stuff", "r") ;
for( i=0; i<=5; i++)
{
fscanf( fp, "%d:%[^:]s:%.2[^:]f\n" , &i, &str, &f);
printf("Hi %s %d %.2f Size:%d\n", str, i, f, strlen(str));
}
Can i Use [^:] to limit float values as above.
Now the output is:
Hi Hello 0 0.00 Size:5
Hi Hello 1 0.00 Size:5
Hi Hello 2 0.00 Size:5
Hi Hello 3 0.00 Size:5
Hi Hello 4 0.00 Size:5
Hi Hello 5 0.00 Size:5
Please tell me how to solve this new problem. Thanks in advance Walter.
You do not need to use %[^:] or anything similar to limit reading
in float values: the parser will stop as soon as it encounters any
character which is not allowed in a float.
But your problem is not exactly where you were expecting. Your
new difficulty is in your fscanf() format where you have %[:]s
This does NOT mean:
"skip leading whitespace, then read a string of characters
until end of file or the next whitespace or a ':' is reached,
leaving the whitespace or ':' in the buffer"
What it *does* mean is:
"do NOT skip any leading whitespace; read a string of
characters (including whitespace) until end of file or a
':' is reached, leaving the ':' in the buffer; then once
that is done, look for the literal character 's' in the
input".
But since your input does not have a literal character 's'
at that point (and cannot have, since you are either at EOF
or at a ':'), the rest of the fscanf() fails, leaving all the
rest of the values to be read unchanged.
To be more clear about this: %[^:] is a format specifier
all by itself, introduced by the '%' (as all format
specifiers are), and with its type being indicated by the '['.
The format specification extends until the next non-escaped ']'
and ends there. Anything after that point is not part of that
format specifier. [^:] is NOT a modifier of a %s format specifier:
it is a format specifier all of its own, with different rules
than %s. For example, %s skips whitespace but %[] does not.