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