C语言sscanf()函数(从字符串读取格式化输入,提取需要的信息)

C语言函数fscanf()(从流 stream 读取格式化输入)(如果成功,返回成功匹配和赋值的个数;否则返回EOF)(分隔符:space、Tab、Enter)


需包含头文件:C 标准库 - <stdio.h>

描述

C 库函数 int sscanf(const char *str, const char *format, ...) 从字符串读取格式化输入。

声明

下面是 sscanf() 函数的声明。

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

参数

  • str – 这是 C 字符串,是函数检索数据的源。
  • format – 这是 C 字符串,包含了以下各项中的一个或多个:空格字符、非空格字符 和 format 说明符。
  • format 说明符形式为 [=%[*][width][modifiers]type=],具体讲解如下:
    在这里插入图片描述
    sscanf 类型说明符:

在这里插入图片描述

  • 附加参数 – 这个函数接受一系列的指针作为附加参数,每一个指针都指向一个对象,对象类型由 format 字符串中相应的 % 标签指定,参数与 % 标签的顺序相同。
  • 针对检索数据的 format 字符串中的每个 format 说明符,应指定一个附加参数。如果您想要把 sscanf 操作的结果存储在一个普通的变量中,您应该在标识符前放置引用运算符(&),例如:
int n;
sscanf (str,"%d",&amp;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 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s\n", month, day, year, weekday );
    
   return(0);
}

让我们编译并运行上面的程序,这将产生以下结果:

March 25, 1989 = Saturday

我在VS上测试(VS上要用sscanf_s)

sscanf_s 取值的时候,需要在每个取值后面指定取值的最大大小。
(而且根据VS提示,貌似还需要是 unsigned int 类型)

_CRT_STDIO_INLINE int __CRTDECL sscanf_s(
            _In_z_                         char const* const _Buffer,
            _In_z_ _Scanf_s_format_string_ char const* const _Format,
            ...)
sscanf_s(inputString, "%s.%s.%s.%s", s1, s1.length, s2, s2.length, s3, s3.length, s4, s4.length); 

示例1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int day, year;
    char weekday[20], month[20], dtm[100];

    strcpy_s(dtm, "Saturday March 25 1989");
    sscanf_s(dtm, "%s %s %d %d", weekday, (unsigned int)sizeof(weekday), month, (unsigned int)sizeof(month), &day, &year);

    printf("%s %d, %d = %s\n", month, day, year, weekday);

    return(0);
}

运行结果:

March 25, 1989 = Saturday

示例2(提取时能默认以空格分割)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char line[1024] = "path=/live/main_stream video_type=7 width=1920 height=1080 image_type=4 video_path=rkispp_scale0";

    const char* p;
    
    p = strstr(line, "path=");

    char path[64];

    if(NULL != p)
        sscanf_s(p, "path=%s", path, (unsigned int)sizeof(path));

    return(0);
}

运行调试结果:
在这里插入图片描述

参考文章1:C 库函数 - sscanf()

参考文章2:sscanf,sscanf_s及其相关用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dontla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值