简体   繁体   中英

Why sscanf does not work for blank string?

I have a problem with sscanf function...

Here is my code:

char str[]="Andrew;;;3454";
char name[20] = {0};
char city[20] = {0};
char age[5] = {0};
char hasDegree[20] = {0};

sscanf(str,"%[^;];%[^;];%[^;];%[^;]",name,city,age,hasDegree);

printf("%s is %s Years Old and live in %s at %s degrees",name,age,city,hasDegree);

The output: Andrew is Years Old and live in at degrees

As you can see, "Andrew" is printed but not "3454" (because there are 2 blank before?)

How to solve it please?

I have declared everything in char voluntarily:)

Thank you !

The [ conversion matches a non-empty set of characters. The empty fields cause the conversion to fail before reading reaches the 3454 field.

In general, I find the scanf family of functions hard to use, especially when error recovery is required (eg, here you could check the return value for the number of fields successfully read, but the recovery would be more complicated than just reading them one by one to begin with). I would suggest strtok or strsep (if available) for parsing fields. Or if you have other reasons to use scanf , read one field at a time and then move the read position past the next ; .

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