English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

Funções do C

Matriz do C

Ponteiro do C

String do C

C Language Structure

C Language File

C Others

C Language Reference Manual

Usage and example of C library function sscanf()

Biblioteca Padrão do C - <stdio.h>

C library function int sscanf(const char *str, const char *format, ...) Read formatted input from a string.

Declaration

Below is the declaration of the sscanf() function.

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

Parameters

  • str -- This is a C string that is the source of data retrieved by the function.

  • format -- This is a C string that contains one or more of the following items:Space characters, non-space charactersFormat specifier.
    The format specifier is in the form of [=%[*][width][modifiers]type=], explained in detail as follows:

ParametersDescription
*This is an optional asterisk indicating that the data is read from the stream stream, but can be ignored, that is, it is not stored in the corresponding parameters.
widthThis specifies the maximum number of characters to be read in the current read operation.
modifiersSpecify a size different from integer (for d, i and n), unsigned integer (for o, u and x) or floating-point type (for e, f and g) for the data pointed to by the corresponding additional parameters: h: short int (for d, i and n), or unsigned short int (for o, u and x) l :长整型(针对 d、i 和 n),或无符号长整型(针对 o、u 和 x),或双精度型(针对 e、f 和 g) L :长双精度型(针对 e、f 和 g)
type一个字符,指定了要被读取的数据类型以及数据读取方式。具体参见下一个表格。

sscanf 类型说明符:

类型合格的输入参数的类型
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 *
  • 附加参数 -- 这个函数接受一系列的指针作为附加参数,每一个指针都指向一个对象,对象类型由 format 字符串中相应的 % 标签指定,参数与 % 标签的顺序相同。

    对于检索数据的 format 字符串中的每个 format 说明符,应指定一个附加参数。如果您想要把 sscanf 操作的结果存储在一个普通的变量中,您应该在标识符前放置引用运算符(&),例如:

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

返回值

如果成功,该函数返回成功匹配和赋值的个数。如果到达文件末尾或发生读错误,则返回 EOF。

在线示例

以下示例演示了 sscanf() 函数的使用。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];
   strcpy(dtm, "Saturday March"); 15 1999";
   sscanf(dtm, "%s %s %d %d", weekday, month, &day, &year);
   printf("%s %d, %d = %s\n", month, day, year, weekday );
    
   return(0);
}

Vamos compilar e executar o programa acima, o que produzirá o seguinte resultado:

Março 15, 1999 = Sábado

Biblioteca Padrão do C - <stdio.h>