sscanf( )函數的用法

來源:互聯網
上載者:User
sscanf( )函數的用法

SSCANF用法:(繼qsort,bsearch,strchr後發現的又一好使的函數)
sscanf與scanf類似,都是用於輸入的,只是後者以鍵盤(stdin)為輸入源,前者以固定字串為輸入源。
例子:
1. 常見用法。
char buf[512] ;
sscanf("123456 ", "%s", buf);//此處buf是數組名,它的意思是將123456以%s的形式存入buf中!
printf("%s\n", buf);
結果為:123456
2. 取指定長度的字串。如在下例中,取最大長度為4位元組的字串。
sscanf("123456 ", "%4s", buf);
printf("%s\n", buf);
結果為:1234
3. 取到指定字元為止的字串。如在下例中,取遇到空格為止字串。
sscanf("123456 abcdedf", "%[^ ]", buf);
printf("%s\n", buf);
結果為:123456
4. 取僅包含指定字元集的字串。如在下例中,取僅包含1到9和小寫字母的字串。
sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf);
printf("%s\n", buf);
結果為:123456abcdedf
當輸入:
sscanf("123456abcdedfBCDEF","%[1-9A-Z]",buf);
printf("%s\n",buf);
結果為:123456
5. 取到指定字元集為止的字串。如在下例中,取遇到大寫字母為止的字串。
sscanf("123456abcdedfBCDEF", "%[^A-Z]", buf);
printf("%s\n", buf);
結果為:123456abcdedf
6、給定一個字串iios/12DDWDFF@122,擷取 / 和 @ 之間的字串,先將 "iios/"過濾掉,再將非'@'的一串內容送到buf中
sscanf("iios/12DDWDFF@122", "%*[^/]/%[^@]", buf);
printf("%s\n", buf);
結果為:12DDWDFF
7、給定一個字串“hello, world”,僅保留world。(注意:“,”之後有一空格)
sscanf(“hello, world”, "%*s%s", buf);
printf("%s\n", buf);
結果為:world
%*s表示第一個匹配到的%s被過濾掉,即hello被過濾了
如果沒有空格則結果為NULL。
代碼如下:
#include <stdio.h>
#include <string.h>
#include <math.h>
char word[1000];
char arr[100][100]; //arr用於儲存以前出現過的單詞
int main()
{
int len, pos;
char temp[100];
while(gets(word) && strcmp(word, "#") != 0)//題目要求不是文章結尾為,注意strcmp用比較用“#”
{
len = strlen(word);//總長度(包括空格)
pos = 0;
int cnt = 0;
// pos加單詞長度一直到>len
while(pos <= len)
{
sscanf(word + pos, "%s", temp); //把一個單詞存入temp,空格省去(sscanf應該是讀到空格截止,對於sscanf,空格很重要)
//word + pos為指標指向位置
//printf("%s++++++++++++++++++++\n",temp);
int k;
for(k = 0; k < cnt; ++k)
if(strcmp(temp, arr[k]) == 0) //如果和以前存入的單詞相同,則不計數
break;
if(k == cnt)
strcpy(arr[cnt++], temp); //把temp存入arr,並計數器cnt加一
pos += strlen(temp) + 1;// +1表示加上空格,最後一次pos肯定會大於len
}
printf("%d\n", cnt);
}
return 0;
}


原文轉自:http://minda-ly.diandian.com/post/2011-02-13/17223519

聯繫我們

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