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

C语言使用strtok实现日期格式转换时if判断失效问题求解

问题原因
  • 核心错误:C语言中不能直接使用==运算符比较字符串内容。==只会对比两个指针指向的内存地址,你的token指针指向输入字符串中截取的月份子串,而"01"这类是存储在只读数据区的字符串常量,二者的内存地址永远不可能相等,因此所有条件判断都不会触发,最终走到else分支默认赋值为December。
  • 额外潜在问题:gets()函数存在缓冲区溢出漏洞,已经被C标准废弃;另外你拼写错误了一月的英文,正确写法为January,不是Januray。
修复方案

使用<string.h>头文件提供的strcmp()函数对比字符串内容,该函数在两个字符串内容完全相等时返回0。修复后完整代码如下:

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

int main()
{
    char date[20];
    char month[20];
    char day[20];
    char year[20];
    char *token;
    const char *sep = "/";

    printf("Enter the date (MM/DD/YYYY): ");
    // 用fgets替代废弃的gets,避免缓冲区溢出
    fgets(date, sizeof(date), stdin);
    // 移除fgets读取到的末尾换行符
    date[strcspn(date, "\n")] = '\0';

    token = strtok(date, sep);

    if (strcmp(token, "01") == 0)
    {
        strcpy(month, "January");
    }
    else if (strcmp(token, "02") == 0)
    {
        strcpy(month, "February");
    }
    else if (strcmp(token, "03") == 0)
    {
        strcpy(month, "March");
    }
    else if (strcmp(token, "04") == 0)
    {
        strcpy(month, "April");
    }
    else if (strcmp(token, "05") == 0)
    {
        strcpy(month, "May");
    }
    else if (strcmp(token, "06") == 0)
    {
        strcpy(month, "June");
    }
    else if (strcmp(token, "07") == 0)
    {
        strcpy(month, "July");
    }
    else if (strcmp(token, "08") == 0)
    {
        strcpy(month, "August");
    }
    else if (strcmp(token, "09") == 0)
    {
        strcpy(month, "September");
    }
    else if (strcmp(token, "10") == 0)
    {
        strcpy(month, "October");
    }
    else if (strcmp(token, "11") == 0)
    {
        strcpy(month, "November");
    }
    else
    {
        strcpy(month, "December");
    }

    token = strtok(NULL, sep);
    strcpy(day, token);

    token = strtok(NULL, sep);
    strcpy(year, token);

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:24:01