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

C语言读取键盘时间戳字符串时输出截断问题求助及替代方案咨询

问题解答

1. 输出分钟被截断的原因及解决

你的printf语句里用%d输出分钟数,当输入00时,%d只会输出0,看起来像是最后一位被截断了。要保持两位数字格式,需要用%02d格式化输出,它会自动为不足两位的数字补前导零。

修改后的printf语句:

printf("You entered %02d/%02d/%d %02d:%02d\n", UserMonthChoice, UserDayChoice, UserYearChoice, UserHourChoice, UserMinutesChoice);

2. 更优的实现方案(适配mktime)

直接用scanf处理输入容易出现缓冲区残留、格式不匹配时的异常问题,推荐用fgets读取整行输入,再用sscanf解析,同时直接适配mktime所需的struct tm结构,减少中间变量转换:

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

int main() {
    char input[100];
    struct tm time_info = {0}; // 初始化结构体,避免未定义行为

    printf("Enter your desired planting date in this format -> MM/DD/YYYY hh:mm.\n");
    printf("For example 04/19/2022 08:00\n");

    // 读取整行输入
    if (fgets(input, sizeof(input), stdin) == NULL) {
        fprintf(stderr, "Failed to read input\n");
        return 1;
    }

    // 解析输入到tm结构体,注意tm_mon是0-11(需减1),tm_year是从1900年开始的偏移量(需减1900)
    if (sscanf(input, "%d/%d/%d %d:%d", &time_info.tm_mon, &time_info.tm_mday, &time_info.tm_year, &time_info.tm_hour, &time_info.tm_min) != 5) {
        fprintf(stderr, "Input format error! Please follow MM/DD/YYYY hh:mm\n");
        return 1;
    }

    // 修正tm结构体的字段
    time_info.tm_mon -= 1;    // 月份转成0-11
    time_info.tm_year -= 1900;// 年份转成从1900年开始的偏移

    // 验证并转换为时间戳
    time_t timestamp = mktime(&time_info);
    if (timestamp == -1) {
        fprintf(stderr, "Invalid date/time\n");
        return 1;
    }

    // 输出验证结果
    printf("You entered: %02d/%02d/%d %02d:%02d\n", 
           time_info.tm_mon + 1, time_info.tm_mday, 
           time_info.tm_year + 1900, time_info.tm_hour, time_info.tm_min);
    printf("Corresponding timestamp: %ld\n", (long)timestamp);

    return 0;
}

方案优势:

  • 用fgets读取整行,避免scanf遗留的换行符或非法输入导致的后续读取异常
  • 直接操作struct tm结构体,无缝对接mktime函数,无需额外变量转换
  • 增加输入格式校验和时间有效性验证,提升程序健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:45:46