sscanf高階用法總結

2021-06-28 00:08:44 字數 1601 閱讀 7313

大家都知道sscanf是乙個很好用的函式,利用它可以從字串中取出整數、浮點數和字串等等。它的使用方法簡單,特別對於整數和浮點數來說。但新手可能並不知道處理字串時的一些高階用法,這裡做個簡要說明吧。

1. 常見用法。

char str[512] = ;

sscanf("123456 ", "%s", str);

printf("str=%s/n", str);

2. 取指定長度的字串。如在下例中,取最大長度為4位元組的字串。

sscanf("123456 ", "%4s", str);

printf("str=%s/n", str);

3. 取到指定字元為止的字串。如在下例中,取遇到空格為止字串。

sscanf("123456 abcdedf", "%[^ ]", str);

printf("str=%s/n", str);

4. 取僅包含指定字符集的字串。如在下例中,取僅包含1到9和小寫字母的字串。

sscanf("123456abcdedfbcdef", "%[1-9a-z]", str);

printf("str=%s/n", str);

5. 取到指定字符集為止的字串。如在下例中,取遇到大寫字母為止的字串。

sscanf("123456abcdedfbcdef", "%[^a-z]", str);

printf("str=%s/n", str);

源**一如下:

#include

#include

char *tokenstring = "12:34:56-7890";

char a1[3], a2[3], a3[3];

int i1, i2;

void main(void)

源**二如下:

#include

#include

char *tokenstring = "12:34:56-7890";

char a1[3], a2[3], a3[3];

int i1, i2;

void main(void)

源**三如下:

#include

#include

char *tokenstring = "12:34:56-7890";

char a1[3], a2[3], a3[3], a4[3], a5[3];

int i1, i2;

void main(void)

方法四如下(以例項說明,原理相同):

/* the following sample illustrates the use of brackets and the

caret (^) with sscanf().

compile options needed: none*/

#include

#include

#include

char *tokenstring = "first,25.5,second,15";

int result, i;

double fp;

char o[10], f[10], s[10], t[10];

void main()

sscanf的高階用法

sscanf的高階用法 printf或者sprintf一定是任何乙個c程式設計師最常見到的函式,與sprintf的作用相反,sscanf通常被用來解析並轉換字串,其格式定義靈活多變,可以實現很強大的字串解析功能。sscanf的原型很簡單,定義如下 include int sscanf const c...

sscanf的高階用法

sscanf的高階用法 總結 2012 04 25 18 50 25 分類 c c sscanf recvbuf,s buf rev sscanf buf,get buf rev 這個是在乙個webserver.c裡面的例子,通過sscanf 語句可以找到和它前面相匹配的語句然後列印出後面需要的東西...

sscanf的高階用法

c c sscanf recvbuf,s buf rev sscanf buf,get buf rev example 1 scanf buf 當輸入的字元中出現 時停止匹配,如果輸入hello world,則buf hello 片 2 scanf 290 buf 當輸入aidc ad時,則buf ...