Reputation: 3752
I'm trying to read through a file that looks like this:
truck, wanted, 4000
truck, for sale, 2000
microwave, for sale, 2
truck, wanted, 4000
but my fscanf
is returning 1
(should be 3
):
fscanf(file,
"%s, %[^,], %d",
items[i].type,
temp,
&items[i].price)
Basically I want to read it like a CSV, first word into first var, second word(s) (either wanted
or for sale
) into temp, and the number into the third var.
Upvotes: 0
Views: 120
Reputation: 320371
fscanf
does not work like that. When you specify %s
format specifier, it reads everything till the next whitespace (or end of input). Which means that your first %s
will read truck,
, i.e. include the comma into the string it reads. %s
does not care that in your format string you placed ,
after %s
and thus kinda "requested" the comma to be left unread. fscanf
does not support such requests. fscanf
does not have any advanced lookahead or pattern matching capabilities. It blindly reads as much as requested by the current format specifier. %s
reads till the next whitespace - that's all it cares about.
If you want to read this as CSV values, you will have to manually guide fscanf
every step of the way. In this case you can use use %[^,]
for all string values. Something like this might work
fscanf(file,
"%[^,], %[^,], %d",
items[i].type,
temp,
&items[i].price)
If you want to skip any leading whitespace, you can use " %[^,], %[^,], %d"
format.
Space before %d
can be omitted, meaning that "%[^,], %[^,],%d"
is the same as "%[^,], %[^,], %d"
.
Upvotes: 4