sscanf 函數用法

來源:互聯網
上載者:User
 

函數功能

sscanf() - 從一個字串中讀進與指定格式相符的資料.

定義

int  sscanf( string str, string fmt, mixed var1, mixed var2 ... );

說明:

sscanf與scanf類似,都是用於輸入的,只是後者以螢幕(stdin)為輸入源,前者以固定字串為輸入源。
其中的format可以是一個或多個 {%[*] [width] [{h | l | I64 | L}]type | ' ' | '/t' | '/n' | 非%符號}

1、 * 亦可用于格式中, (即 %*d 和 %*s) 加了星號 (*) 表示跳過此資料不讀入. (也就是不把此資料讀入參數中)

 

2、{a|b|c}表示a,b,c中選一,[d],表示可以有d也可以沒有d。

 

3、width表示讀取寬度。

 

4、{h | l | I64 | L}:參數的size,通常h表示單位元組size,I表示2位元組 size,L表示4位元組size(double例外),l64表示8位元組size。

5、type :這就很多了,就是%s,%d之類。

 

6、特別的:%*[width] [{h | l | I64 | L}]type 表示滿足該條件的被過濾掉,不會向目標參數中寫入值

 

 

支援集合操作:

     %[a-z] 表示匹配a到z中任一字元,貪婪性(儘可能多的匹配)

 

     %[aB'] 匹配a、B、'中一員,貪婪性

     %[^a] 匹配非a的任一字元,貪婪性

一個全面的樣本

#include <string>
#include <stdio.h>

int main(int argc,char *argv[])
{
 char buf[128];

 //常見用法,去前兩個字元
 sscanf("123456 ", "%2s", buf);
    printf("buf:%s/n", buf);
 
 //擷取/和@之間的字串怎麼做
 sscanf("iios/12DDWDFF@122", "%*[^/]/%[^@]", buf );
 printf( "buf:%s/n", buf );

 //取僅包含指定字元集的字串,取僅包含1到9和小寫字母的字串。
 sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf);
    printf("buf:%s/n", buf);

 //取到指定字元為止的字串,取遇到空格為止字串
 sscanf("123456 abcdedf", "%[^ ]", buf);
    printf("str:%s/n", buf);

 //取到指定字元集為止的字串,取遇到大寫字母為止的字串
 sscanf("123456abcdedfBCDEF", "%[^A-Z]", buf);
    printf("buf:%s/n", buf);

 //取第二個單詞, %*s表示忽略第一個單詞,取第二個單詞
 sscanf("hi hello", "%*s%s", buf);
 printf("buf:%s/n", buf);

 int a = 0,b = 0,c = 0;
 sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c);
 printf("a=%d,b=%d,c=%d/n", a,b,c);

 //使用者名稱和密碼用:分隔,取出使用者名稱和密碼
 /*
  1.%*[ ]取出前面的空格
  2.%127[^:]取前面127個字元,遇到:結束
  3.':'符分割字串
  4.%127[^ ]取前面127個字元,遇到空格結束
 */
 char user_name[20],password[20];
 sscanf("  admin :admin123", "%*[ ]%127[^:]:%127[^ ]", user_name, password);
 sscanf(user_name, "%s", user_name);//去除後面的空格
 printf("user_name:%s,password:%s/n", user_name,password);

 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.