简体   繁体   中英

fscanf not matching properly

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.

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, , ie 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" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM