sscanf/scanf特殊用法

來源:互聯網
上載者:User

%[ ] 的用法:%[ ]表示要讀入一個字元集合, 如果[ 後面第一個字元是”^”,則表示反意思。

                     [ ]內的字串可以是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點最致命,越複雜的功能往往執行效率越低下。而一些簡單的字串分析我們可以自已處理。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.