scanf 的超级用法

scanf格式控制字符串%[]

[Reading Undelimited strings]
*To read strings not delimited by whitespace characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The set of characters in brackets is referred to as a control string. The corresponding input field is read up to the first character that does not appear in the control string. 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.

举一些例子:
     对于 const char* p = "12232114687ABC12356";
     sscanf(p,"%[123]",buf); // 就把是'1'或'2'或'3'的字读读到buf中,直到遇到一个不是'1'且不是'2'且不是'3'的字符,于是执行后buf应该是"1223211";
     %[123]等同于%[231],等同于%[321]……,列表中的顺序是无所谓的;
     %[123]也等同于%[1-3]或%[3-1],也就是“1至3”,对于连续的字符列表这样写就很简单,比如%[a-z]等同%[abc…省略…z];
     想想看,%[3-14]应该等同于什么?是“3至14”吗?当然不是,因为[]中的是字符,而不是数字,所以%[3-14]应该等同于%[3214],等同于%[1234];
     同理,想只取字母,那就可以写成%[A-Za-z];
     如果列表的第一个字母是^,那么正好相反,比如%[^A-Za-z]的意思就是取字母之外的所有字符。
     对于字符串"abDEc123"如果想按照字母和数字读到两个字符串中就应该是 "%[a-zA-Z]%[0-9]",buf1,buf2 ;
     假如我想取一行字符,该怎么办?"%s"是不行的,因为%s遇到空白字符(空格、制表符、/r、/n)就结束了,所以可以写成 "%[^/n]%*c",%[^/n]的作用刚才讲过了,就是读/n之外的所有字符,也就是说读到/n为止,%*c的作用就是把/n去掉,否则再次读的时候一直遇到的都是/n;
     所有对%s起作用的控制,都可以用于%[],比如"%*[^/n]%*c"就表示跳过一行,"%-20[^/n]"就表示读取/n前20个字符。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值