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

如何使用std::cin正确读取mm/dd/yyyy格式的日期

C++ 读取 mm/dd/yyyy 格式日期的正确实现方案

原代码 std::cin >> month >> day >> year 失效的核心原因:输入中存在 / 分隔符,std::cin 提取int类型值时遇到非数字字符会直接终止提取流程,导致后续日期值读取失败。

下面是三种常用的实现方案:

  • 方案1:显式读取分隔符
    额外定义char类型变量接收输入中的斜杠,代码示例:

    int month, day, year;
    char separator;
    std::cin >> month >> separator >> day >> separator >> year;
    

    如果需要严格校验输入格式,可增加分隔符合法性判断:

    if (separator != '/') {
        // 输入格式错误的自定义处理逻辑
    }
    
  • 方案2:使用scanf格式化读取
    利用C语言scanf的格式匹配能力直接适配带斜杠的输入格式,代码更简洁:

    int month, day, year;
    scanf("%d/%d/%d", &month, &day, &year);
    

    格式串%d/%d/%d会自动匹配输入中的斜杠,无需额外处理分隔符变量,适合固定格式的输入场景。

  • 方案3:整行读取后解析
    适合需要做复杂格式校验、或者输入格式存在变体的场景,步骤为读取整行输入→按斜杠分割→子串转整数,代码示例:

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <vector>
    
    std::vector<std::string> split(const std::string& s, char delimiter) {
        std::vector<std::string> parts;
        std::stringstream ss(s);
        std::string temp;
        while (std::getline(ss, temp, delimiter)) {
            parts.push_back(temp);
        }
        return parts;
    }
    
    int main() {
        std::string date_input;
        std::getline(std::cin, date_input);
        auto date_parts = split(date_input, '/');
        if (date_parts.size() == 3) {
            int month = std::stoi(date_parts[0]);
            int day = std::stoi(date_parts[1]);
            int year = std::stoi(date_parts[2]);
            // 可在此处增加月、日、年的合法性校验逻辑
        }
        return 0;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:18:03