简体   繁体   English

为什么 sscanf 不适用于空白字符串?

[英]Why sscanf does not work for blank string?

I have a problem with sscanf function...我对 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 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?)如您所见,打印的是“Andrew”而不是“3454”(因为之前有2个空白?)

How to solve it please?请问怎么解决?

I have declared everything in char voluntarily:)我自愿在 char 中声明了所有内容:)

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.空字段会导致转换在读取到达3454字段之前失败。

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).总的来说,我发现scanf系列函数很难使用,尤其是在需要错误恢复时(例如,在这里您可以检查成功读取的字段数的返回值,但恢复会比仅读取一个更复杂从一个开始)。 I would suggest strtok or strsep (if available) for parsing fields.我建议使用strtokstrsep (如果可用)来解析字段。 Or if you have other reasons to use scanf , read one field at a time and then move the read position past the next ;或者,如果您有其他原因使用scanf ,一次读取一个字段,然后将读取的 position 移过下一个字段; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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