You need to enable JavaScript to run this app. C语言程序按分号拆分字符串的sscanf代码修正问题
优惠活动
大模型
产品
解决方案
定价
更多

C语言程序按分号拆分字符串的sscanf代码修正问题

分号分割字符串的代码问题与修正方案

原有代码失效的核心原因

你的实现没有达到预期效果,本质是对sscanf的格式符行为认知存在偏差:

  • %s的匹配规则为读取连续非空白字符序列,直到遇到空白字符、字符串终止符才停止,不会将分号作为匹配的终止边界
  • 按照原代码的格式串"%s;%s"执行时,程序会把完整的Hello;World字符串全部作为第一个%s的匹配内容读入store_hello,后续格式串中的分号找不到对应匹配位置,最终store_world数组未被写入有效内容,仅保留栈上的随机垃圾值,无法实现分割效果。

两种可落地的修正实现

方案1:调整sscanf格式串完成分割

利用sscanf的字符集匹配语法,通过%[^;]指定“读取所有不属于分号的字符”,同时补充宽度限制避免缓冲区溢出:

#include <stdio.h>
int main() {
    char* buffer = "Hello;World";
    char store_hello[10], store_world[10];
    int total_read;
    // 格式说明:最多读取9个非分号字符存入目标数组,匹配分号后再读取后续非空白序列
    total_read = sscanf(buffer, "%9[^;];%9s", store_hello, store_world);

    printf("成功匹配的字段数:%d\n", total_read);
    printf("Value in first variable: %s\n", store_hello);
    printf("Value in second variable:  %s\n", store_world);
    return 0;
}

该代码的运行输出和预期完全一致:

成功匹配的字段数:2
Value in first variable: Hello
Value in second variable:  World

注:格式串中的数字9是为了匹配10字节的目标数组长度,预留1字节位置存储字符串终止符,防止读入内容超过数组边界造成内存溢出。

方案2:使用标准库strtok函数实现通用分割

如果后续需要扩展分割逻辑、兼容多类分隔符,更推荐使用<string.h>头文件提供的strtok函数实现分割,需要注意两个使用要点:

  • strtok会直接修改传入的原字符串,将分隔符位置替换为字符串终止符,因此不能直接传入指向字符串字面量的只读指针(也就是原代码中char* buffer = "Hello;World"这类写法,传入strtok会触发只读内存访问错误),需要将原字符串改为可写的字符数组
  • 第一次调用strtok时传入待分割的目标字符串,后续调用传入NULL即可继续分割剩余内容
    示例实现:
#include <stdio.h>
#include <string.h>
int main() {
    char buffer[] = "Hello;World"; // 必须为可修改的字符数组,不可直接使用字符串字面量指针
    char *current_token;
    int field_idx = 1;

    // 指定分隔符为分号
    current_token = strtok(buffer, ";");
    while (current_token != NULL) {
        printf("Value in %d variable: %s\n", field_idx, current_token);
        current_token = strtok(NULL, ";");
        field_idx++;
    }
    return 0;
}

运行输出:

Value in 1 variable: Hello
Value in 2 variable: World

内容的提问来源于stack exchange,提问作者jms1980

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 23:15:03