芯路恒电子技术论坛

 找回密码
 立即注册
热搜: 合集
查看: 168|回复: 0

【C语言】【字符串】字符串解析函数sscanf详解

[复制链接]

该用户从未签到

75

主题

94

帖子

1055

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
1055
发表于 2025-4-8 17:24:37 | 显示全部楼层 |阅读模式

基本语法

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

str:要解析的源字符串;

format:格式控制字符串;

...:用于保存解析结果的变量地址;

返回值:成功读取并赋值的字段数量。

常见用法及示例

1.基本类型的读取

#include <stdio.h>

int main() {
    const char *str = "42 3.14 A";
    int i;
    float f;
    char c;

    sscanf(str, "%d %f %c", &i, &f, &c);

    printf("int: %d, float: %.2f, char: %c\n", i, f, c);
    return 0;
}

输出:

int: 42, float: 3.14, char: A

2.字符串的读取

#include <stdio.h>

int main() {
    const char *str = "Hello World";
    char word1[10], word2[10];

    sscanf(str, "%s %s", word1, word2);

    printf("First word: %s, Second word: %s\n", word1, word2);
    return 0;
}

注意:%s 读取遇到空白符会停止(空格、换行、Tab)。

输出:

First word: Hello, Second word: World

3.限制字符串长度

char str[] = "abcdef";
char buf[4];

sscanf(str, "%3s", buf);  // 最多读取3个字符 + 末尾自动加\0
printf("buf: %s\n", buf); // 输出:abc

输出:

buf: abc

4.解析日期格式字符串

#include <stdio.h>

int main() {
    const char *date = "2025-04-08";
    int year, month, day;

    sscanf(date, "%d-%d-%d", &year, &month, &day);
    printf("Year: %d, Month: %d, Day: %d\n", year, month, day);
    return 0;
}

输出:

Year: 2025, Month: 4, Day: 8

5.跳过字段(使用*)

#include <stdio.h>

int main() {
    const char *str = "Name: John Age: 25";
    int age;

    sscanf(str, "Name: %*s Age: %d", &age);  // 忽略名字
    printf("Age: %d\n", age);
    return 0;
}

输出:

Age: 25

6.读取包含空格的整行(scanset %[^\n]

#include <stdio.h>

int main() {
    const char *str = "Title: The Great Gatsby";
    char title[50];

    sscanf(str, "Title: %[^\n]", title);
    printf("Book title: %s\n", title);
    return 0;
}

输出:

Book title: The Great Gatsby

7.解析进制和科学计数法

#include <stdio.h>

int main() {
    const char *str = "0xFF 077 3.14e2";
    int hex, oct;
    float sci;

    sscanf(str, "%x %o %e", &hex, &oct, &sci);
    printf("Hex: %d, Oct: %d, Sci: %.2f\n", hex, oct, sci);
    return 0;
}

输出:

Hex: 255, Oct: 63, Sci: 314.00

8.用返回值判断解析成功的字段数量

#include <stdio.h>

int main() {
    const char *str = "123 abc";
    int num;
    char word[10];

    int ret = sscanf(str, "%d %s", &num, word);
    if (ret == 2) {
        printf("Parsed: %d and %s\n", num, word);
    } else {
        printf("Parsing failed, only %d items matched.\n", ret);
    }
    return 0;
}

输出:

Parsed: 123 and abc

使用注意事项总结

注意点 说明
%s 默认不读取空格 如果要读取带空格的字符串,用 %[^\n]%[^\t]
注意缓冲区溢出 %s 提供的数组必须足够大或限制读取长度
返回值用于验证匹配字段 推荐使用 sscanf 的返回值判断解析是否成功
类型匹配必须准确 %f 对应 float%lf 对应 double
忽略字段用 * 可以省略不需要保存的字段
%n 可用于获取当前位置 返回已读取的字符数,用于更复杂的拆分
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|Archiver|芯路恒电子技术论坛 |鄂ICP备2021003648号

GMT+8, 2025-4-16 08:05 , Processed in 0.184669 second(s), 31 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

快速回复 返回顶部 返回列表