linux sscanf 空格,sscanf 特殊分隔符(逗号)

一、sscanf在直接处理逗号分隔符的时候,会发生错误。

程序如下:

char *s = "aaa,bbb,ccc,ddd";

char a[32],b[32],c[32],d[32];

sscanf(s, "%s,%s,%s,%s\n", a, b, c, d);

printf("[%s][%s][%s][%s]\n", a, b, c, d);

结果为:

develop:/home/leon/test # ./a.out

[aaa,bbb,ccc,ddd][][][]

二、解决。将sscanf内的格式化输出改为以下形式:

sscanf(s, "%[^,],%[^,],%[^,],%s", a, b, c, d);

结果为:

develop:/home/leon/test # ./a.out

[aaa][bbb][ccc][ddd]

三、以下为MDSN的说明:

To read strings not delimited by space characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The corresponding input field is read up to the first character that does not appear in the bracketed character set. If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set.

Note that %[a-z] and %[z-a] are interpreted as equivalent to %[abcde...z]. This is a common scanf function extension, but note that the ANSI standard does not require it.

理解:

%[]   指定字符集,即加了字符规则的'%s

^     取反

%[^,] 取非','的内容,直到遇到','

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值