sscanf() - C語言庫函式


C庫函式 int sscanf(const char *str, const char *format, ...) 讀取輸入一個字串格式化。

宣告

以下是sscanf() 函式的宣告。

int sscanf(const char *str, const char *format, ...)

引數

  • str -- 這是C字串函式流程作為其源中檢索資料。

  • format --這是C字串,其中包含一個或多個以下專案:空白字元,非空白字元和格式說明符

    格式規範遵循這個原型: [=%[*][width][modifiers]type=]

引數 描述
* This is an optional starting asterisk indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument.
width This specifies the maximum number of characters to be read in the current reading operation
modifiers Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data yiibaied by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)
type A character specifying the type of data to be read and how it is expected to be read. See next table.

fscanf型別說明:

type 合格輸入 引數型別
c Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end. char *
d Decimal integer: Number optionally preceeded with a + or - sign int *
e,E,f,g,G Floating yiibai: Decimal number containing a decimal yiibai, optionally preceeded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4 float *
o OctalInteger: int *
s String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab). char *
u Unsigned decimal integer. unsigned int *
x,X Hexadecimal Integer int *
  • other arguments --  預計此功能作為額外的引數的指標指向物件的型別由它們相應的%標記指定的格式字串內,以相同的順序,每一個序列。

    對於每一個檢索資料的格式字串格式說明,一個額外的引數應符合規定。如果要儲存一個你應該先於它的識別符號參照操作的常規變數上一個sscanf的操作結果,即一個符號符號(&),像:int n; sscanf (str,"%d",&n);

返回值

如果成功,函式返回充滿變數的數量。在故障之前可以成功地讀取任何資料輸入的情況下,返回EOF。

例子

下面的例子演示了如何使用 sscanf() 函式。

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   strcpy( dtm, "Saturday March 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s
", month, day, year, weekday );
    
   return(0);
}

讓我們編譯和執行上面的程式,這將產生以下結果:

March 25, 1989 = Saturday