2024年5月20日发(作者:)
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 %[]. This is a common scanf function extension, but note that
the ANSI standard does not require it.
举一些例子:
对于 const char* p = "ABC12356";
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个字符。
scanf/sscanf 格式的特殊控制
代码
scanf中一种很少见但很有用的转换字符:[...]和[ ^...]。
#include
发布者:admin,转转请注明出处:http://www.yc00.com/web/1716162331a2726306.html
评论列表(0条)