sscanf/scanf特殊用法

来源:互联网 发布:数控法兰克系统编程 编辑:程序博客网 时间:2024/04/28 19:49

%[ ] 的用法:%[ ]表示要读入一个字符集合, 如果[ 后面第一个字符是”^”,则表示反意思。

                     [ ]内的字符串可以是1或更多字符组成。空字符集(%[])是违反规定的,可

                     导致不可预知的结果。%[^]也是违反规定的。
         

%[a-z] 读取在 a-z 之间的字符串,如果不在此之前则停止,如

              char s[]="hello, my friend” ;         // 注意: ,逗号在不 a-z之间

              sscanf( s, “%[a-z]”, string ) ; // string=hello

%[^a-z] 读取不在 a-z 之间的字符串,如果碰到a-z之间的字符则停止,如

              char s[]="HELLOkitty” ;         // 注意: ,逗号在不 a-z之间

              sscanf( s, “%[^a-z]”, string ) ; // string=HELLO

%*[^=]    前面带 * 号表示不保存变量。跳过符合条件的字符串。

              char s[]="notepad=1.0.0.1001" ;

       char szfilename [32] = "" ;

       int i = sscanf( s, "%*[^=]", szfilename ) ; // szfilename=NULL,因为没保存

int i = sscanf( s, "%*[^=]=%s", szfilename ) ; // szfilename=1.0.0.1001

%40c      读取40个字符

              The run-time

library does not automatically append a null terminator

to the string, nor does reading 40 characters

automatically terminate the scanf() function. Because the

library uses buffered input, you must press the ENTER key

to terminate the string scan. If you press the ENTER before

        the scanf() reads 40 characters, it is displayed normally,

        and the library continues to prompt for additional input

        until it reads 40 characters

%[^=]     读取字符串直到碰到’=’号,’^’后面可以带更多字符,如:

              char s[]="notepad=1.0.0.1001" ;

       char szfilename [32] = "" ;

       int i = sscanf( s, "%[^=]", szfilename ) ; // szfilename=notepad     

       如果参数格式是:%[^=:] ,那么也可以从 notepad:1.0.0.1001读取notepad

             

使用例子:

       char s[]="notepad=1.0.0.1001" ;

char szname [32] = "" ;

char szver [32] = “” ;

sscanf( s, "%[^=]=%s", szname , szver ) ; // szname=notepad, szver=1.0.0.1001

总结:%[]有很大的功能,但是并不是很常用到,主要因为:

1、许多系统的 scanf 函数都有漏洞. (典型的就是 TC 在输入浮点型时有时会出错).

2、用法复杂, 容易出错.

3、编译器作语法分析时会很困难, 从而影响目标代码的质量和执行效率.

个人觉得第3点最致命,越复杂的功能往往执行效率越低下。而一些简单的字符串分析我们可以自已处理。