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