%[ ] 的用法:%[ ]表示要讀入一個字元集合, 如果[ 後面第一個字元是”^”,則表示反意思。
[ ]內的字串可以是1或更多字元組成。Null 字元集(%[])是違反規定的,可
導致不可預知的結果。%[^]也是違反規定的。
%[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點最致命,越複雜的功能往往執行效率越低下。而一些簡單的字串分析我們可以自已處理。