You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整C语言代码,用sscanf解析YYYYMMDDHH格式日期字符串?

问题分析与修正方案

原代码存在几个关键问题,导致无法正确解析日期字符串:

1. 变量类型定义错误

year、month、day、hour被定义为单个char类型,但它们需要存储多字符的子串(比如年份是4位),必须定义为字符数组,且要预留字符串结束符\0的空间。

2. 数组长度不足

datetime存储的是10位日期字符串,C语言字符串需要额外1位存储结束符,因此数组长度应设为11,否则sprintf会导致缓冲区溢出,触发未定义行为。

3. sscanf参数传递错误

使用%s格式符时,必须传递字符数组的指针(数组名本身就是指针),原代码传递单个char变量,会导致内存访问错误。

4. 冗余头文件

math.h在代码中未被使用,可以移除。


修正后的字符串解析版本

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

int main()
{
    // 预留结束符空间,长度设为11
    char datetime[11];
    // 定义足够长度的字符数组:年份4位+结束符=5,其他2位+结束符=3
    char year[5], month[3], day[3], hour[3];

    sprintf(datetime, "2022092300");
    // %4s读取4个字符,%2s读取2个字符,依次分配到对应数组
    sscanf(datetime, "%4s%2s%2s%2s", year, month, day, hour);
    
    printf("year is %s, month is %s, day is %s, hour is %s\n", year, month, day, hour);

    return 0;
}

额外优化:解析为整数类型

如果不需要字符串形式,而是需要整数类型的年、月、日、时,可以直接用%d格式符解析,代码更简洁:

#include <stdio.h>

int main()
{
    char datetime[11];
    int year, month, day, hour;

    sprintf(datetime, "2022092300");
    sscanf(datetime, "%4d%2d%2d%2d", &year, &month, &day, &hour);
    
    printf("year is %d, month is %d, day is %d, hour is %d\n", year, month, day, hour);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:05:21