Latest web development tutorials

C library functions - sscanf ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionsint sscanf (const char * str, const char * format, ...) to read formatted input from a string.

statement

Here it is () statement sscanf function.

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

parameter

  • str - This is a C string, the function retrieves the source data.
  • format - This is a C string containing the following items in one or more of:space characters, non-space charactersand format specifiers.
    format specifier of the form[=% [*] [width ] [modifiers] type =], the specific explanation as follows:
参数描述
*这是一个可选的星号,表示数据是从流 stream 中读取的,但是可以被忽视,即它不存储在对应的参数中。
width这指定了在当前读取操作中读取的最大字符数。
modifiers为对应的附加参数所指向的数据指定一个不同于整型(针对 d、i 和 n)、无符号整型(针对 o、u 和 x)或浮点型(针对 e、f 和 g)的大小: h :短整型(针对 d、i 和 n),或无符号短整型(针对 o、u 和 x) l :长整型(针对 d、i 和 n),或无符号长整型(针对 o、u 和 x),或双精度型(针对 e、f 和 g) L :长双精度型(针对 e、f 和 g)
type一个字符,指定了要被读取的数据类型以及数据读取方式。具体参见下一个表格。

sscanf type specifier:

类型合格的输入参数的类型
c单个字符:读取下一个字符。如果指定了一个不为 1 的宽度 width,函数会读取 width 个字符,并通过参数传递,把它们存储在数组中连续位置。在末尾不会追加空字符。char *
d十进制整数:数字前面的 + 或 - 号是可选的。int *
e,E,f,g,G浮点数:包含了一个小数点、一个可选的前置符号 + 或 -、一个可选的后置字符 e 或 E,以及一个十进制数字。两个有效的实例 -732.103 和 7.12e4float *
o八进制整数。int *
s字符串。这将读取连续字符,直到遇到一个空格字符(空格字符可以是空白、换行和制表符)。char *
u无符号的十进制整数。unsigned int *
x,X十六进制整数。int *
  • Additional parameters - This function takes a pointer as a series of additional parameters, each a pointer to an object, the object type is specified by the format string corresponding% label% label the order parameter is the same.

    For format string to retrieve data for each format specifier, specify an additional parameter. If you want to put in an ordinary variable, you should be placed in front of the identifier reference result storage sscanf operator operator (&), for example:

        int n;
        sscanf (str,"%d",&amp;n);
    

return value

If successful, the function returns the number of successfully matched and assigned. If you reach the end of the file or a read error occurs, it returns EOF.

Examples

The following example demonstrates the sscanf () function is used.

#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\n", month, day, year, weekday );
    
   return(0);
}

Let's compile and run the above program, which will result in the following:

March 25, 1989 = Saturday

C standard library - <stdio.h> C standard library - <stdio.h>