[英]Why sscanf does not work for blank string?
我對 sscanf function 有問題...
這是我的代碼:
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);
output: Andrew is Years Old and live in at degrees
如您所見,打印的是“Andrew”而不是“3454”(因為之前有2個空白?)
請問怎么解決?
我自願在 char 中聲明了所有內容:)
謝謝 !
[
轉換匹配一組非空字符。 空字段會導致轉換在讀取到達3454
字段之前失敗。
總的來說,我發現scanf
系列函數很難使用,尤其是在需要錯誤恢復時(例如,在這里您可以檢查成功讀取的字段數的返回值,但恢復會比僅讀取一個更復雜從一個開始)。 我建議使用strtok
或strsep
(如果可用)來解析字段。 或者,如果您有其他原因使用scanf
,一次讀取一個字段,然后將讀取的 position 移過下一個字段;
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.