C 库 - sscanf() 函数



C 库 sscanf(const char *str, const char *format, ...) 函数从字符串中读取格式化的输入,并将结果存储到提供的变量中。

语法

以下是 C 库 sscanf() 函数的语法:

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

参数

此函数接受以下参数:

  • str: 要读取的输入字符串。
  • format: 指定如何解释输入字符串的格式字符串。
  • ...: 指向将存储提取值的变量的其他参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

该函数返回成功匹配和赋值的输入项数。如果输入与格式字符串不匹配,则函数返回 EOF 或成功匹配和赋值的项数(直至该点)。

格式说明符

以下是格式说明符列表:

  • %d: 读取整数。
  • %f: 读取浮点数。
  • %s: 读取字符串。
  • %c: 读取字符。
  • %x: 读取十六进制整数。
  • %o: 读取八进制整数。
  • %u: 读取无符号整数。

示例 1:解析整数和字符串

以下代码演示了从输入中解析整数和字符串。

以下是 C 库 sscanf() 函数的示例。

Open Compiler
#include <stdio.h> int main() { const char *input = "42 Alice"; int number; char name[20]; int result = sscanf(input, "%d %s", &number, name); printf("Parsed number: %d\n", number); printf("Parsed name: %s\n", name); printf("Number of items matched: %d\n", result); return 0; }

输出

以上代码产生以下结果:

Parsed number: 42
Parsed name: Alice
Number of items matched: 2

示例 2:解析十六进制数和字符

此示例从输入字符串中解析十六进制数和字符。

Open Compiler
#include <stdio.h> int main() { const char *input = "0xA5 Z"; int hexValue; char character; int result = sscanf(input, "%x %c", &hexValue, &character); printf("Parsed hex value: %x\n", hexValue); printf("Parsed character: %c\n", character); printf("Number of items matched: %d\n", result); return 0; }

输出

执行以上代码后,我们将得到以下结果:

Parsed hex value: a5
Parsed character: Z
Number of items matched: 2
广告