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 = "12232114687ABC12356";
sscanf(p,"%[123]",buf); // 就把是'1'或'2'或'3'的字读读到buf中,直到遇到一个不是'1'且不是c语言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 = "12232114687ABC12356";
sscanf(p,"%[123]",buf); // 就把是'1'或'2'或'3'的字读读到buf中,直到遇到一个不是'1'且不是c语言scanf能输入中文吗'
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;
%[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个字符。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论