C语言sscanf()函数(从字符串读取格式化输入,提取需要的信息) 您所在的位置:网站首页 c语言指针字符串输入 C语言sscanf()函数(从字符串读取格式化输入,提取需要的信息)

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

2024-07-08 06:55| 来源: 网络整理| 查看: 265

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

需包含头文件:C 标准库 -

文章目录 描述声明参数返回值实例我在VS上测试(VS上要用sscanf_s)示例1示例2(提取时能默认以空格分割)

描述

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",;n); 返回值

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

实例

下面的实例演示了 sscanf() 函数的用法。

#include #include #include 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 #include #include 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 #include #include 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及其相关用法



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有