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

C++日期转年内天数程序调试:输入横杠致年份为负的问题求助

解决C++中MM-DD-YYYY格式日期输入导致年份为负数的问题

问题原因

原代码直接用cin >> month >> day >> year读取输入,当输入01-24-2008这类带横杠的日期时,C++输入流会把-识别为负数符号:读取完01作为month后,-24会被解析为day的值(24),最后-2008被赋值给year,导致年份变成负数。

解决方法

在读取每个日期分量时,显式处理分隔符-。通过声明一个字符变量接收横杠,让输入流正确跳过这些分隔符,避免将其识别为负数符号。

修改后的完整代码

#include <iostream>
using namespace std;

int main() {
  int month, day, year, day_num = 0;
  char dash; // 用于接收日期中的横杠分隔符
  cout << "Enter date in format (MM-DD-YYYY): ";
  cin >> month >> dash >> day >> dash >> year;

  // 各月份的天数数组
  int days_in_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  // 判断闰年
  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
    days_in_month[1] = 29;
  }

  // 计算当年第几天
  for (int i = 0; i < month - 1; i++) {
    day_num += days_in_month[i];
  }
  day_num += day;

  cout << "Day number of year: " << day_num << endl;

  if (days_in_month[1] == 29) {
    cout << year << " is a leap year." << endl;
  } else {
    cout << year << " is not a leap year." << endl;
  }

  return 0;
}

额外提示

如果需要更严谨的输入验证,可以添加检查逻辑:比如确认dash确实是'-',或者验证月份在1-12之间、日期对应月份的合法天数等,避免非法输入导致程序异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:10:30