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

C++从Linux标准输入流读取日期并校验输出对应星期的实现问题

解决方案

核心背景说明

通过Linux管道传入程序的内容默认会被写入标准输入流,也就是C++中cin对应的流,你完全不需要使用freopen或者额外的文件操作接口,直接读取cin即可,不需要主动向用户索要输入。


具体修改点

1. 修正头文件引用

你当前的头文件没有加尖括号,且引入了很多用不上的依赖,修正后只需要保留iostream即可:

#include <iostream>
using namespace std;

2. 正确解析带/的日期格式

用char变量接收分隔符即可,cin会自动跳过输入前导空白,且读取数字时会自动识别07和7都是整数7,不需要额外处理:

int year, month, day;
char sep1, sep2;
// 读取顺序:年 -> 第一个分隔符 -> 月 -> 第二个分隔符 -> 日
// 读取失败或者分隔符不是/直接判错
if (!(cin >> year >> sep1 >> month >> sep2 >> day) || sep1 != '/' || sep2 != '/') {
    cout << "Error: invalid date" << endl;
    return 1;
}

3. 补全日期合法性校验

需要校验月份范围、日期范围,同时处理闰年2月的特殊情况:

// 判断是否为闰年
bool is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// 按顺序存1-12月的最大天数
int days_in_month[] = {31, 28 + is_leap, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 校验月、日是否合法
if (month < 1 || month > 12 || day < 1 || day > days_in_month[month - 1]) {
    cout << "Error: invalid date" << endl;
    return 1;
}

像示例中3/1/2022这种顺序错误的输入,读取后year=3、month=1、day=2022,会因为天数超出1月最大天数31被判错,符合要求。

4. 修正星期计算逻辑

你用的基姆拉尔森公式需要特殊处理1月、2月:这两个月要当作上一年的13月、14月计算,否则结果会出错。调整后刚好可以匹配示例中0对应Monday、6对应Sunday的要求:

// 处理1、2月的特殊情况
int y = year, m = month;
if (m == 1 || m == 2) {
    m += 12;
    y--;
}
// 基姆拉尔森公式计算星期,结果0=Monday 1=Tuesday ... 6=Sunday
int w = (day + 2*m + 3*(m+1)/5 + y + y/4 - y/100 + y/400) % 7;
const char* weekdays[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

完整可运行代码

#include <iostream>
using namespace std;

int main() {
    int year, month, day;
    char sep1, sep2;

    if (!(cin >> year >> sep1 >> month >> sep2 >> day) || sep1 != '/' || sep2 != '/') {
        cout << "Error: invalid date" << endl;
        return 1;
    }

    bool is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    int days_in_month[] = {31, 28 + is_leap, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month < 1 || month > 12 || day < 1 || day > days_in_month[month - 1]) {
        cout << "Error: invalid date" << endl;
        return 1;
    }

    int y = year, m = month;
    if (m == 1 || m == 2) {
        m += 12;
        y--;
    }
    int w = (day + 2*m + 3*(m+1)/5 + y + y/4 - y/100 + y/400) % 7;
    const char* weekdays[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    cout << w << " " << weekdays[w] << endl;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:39:04