NextDate问题
给出一个年月日,求其下一天是否存在,使用driver函数从文件中读取数据数据格式为“%d-%d-%d”
代码如下
// // main.cpp // Data // #include <iostream> #include <vector> #include <fstream> #include <stdio.h> #include <string.h> #include <cstring> using namespace std; vector<string> trans(string data){ vector<string> res; char tem[data.length()+1]; strcpy(tem, data.c_str()); char* pch =strtok(tem,"-"); while(pch) { res.push_back(string(pch)); pch = strtok(NULL, "-"); } return res; } string NextDate(string data){ vector<string> res=trans(data); if (res.size()!=3) { return "日期格式错误。"; } int year=atoi(res[0].c_str()); int month=atoi(res[1].c_str()); int day=atoi(res[2].c_str()); bool isspcyear=((year%4==0)&&(year%100!=0))||(year%400==0); int datatime[12]={31,29,31,30,31,30,31,31,30,31,30,31}; if(year<1900||year>2200){ return "日期年份错误。"; }else if (month<1||month>12){ return "日期月份错误。"; }else if (day>datatime[month-1]||day<1){ return "日期日错误。"; } else if (month==2){ if (!isspcyear) { if (month==2&&day==29) { return "日期日错误。"; } } } day++; if (month==2) { if (isspcyear) { if (day>29) { month=3; day=1; } } else{ if (day>28) { month=3; day=1; } } }else{ if (day>datatime[month-1]) { month++; day=1; if (month>12) { month=1; year++; } } } char res_num[50]; sprintf(res_num,"%d-%d-%d",year,month,day); return string(res_num); } void driver(){ ifstream fin; fin.open("/测试用例.txt"); //保存测试用例 ofstream fout; fout.open("/测试结果.txt"); //保存测试结果 string temp1,temp2; int i=0; fout << "输入\t\t结果\t\t预期结果\t\t预期是否正确"<< endl; while (fin >> temp1) { if (i%2==0) { fout << temp1 << "\t" << NextDate(temp1) << "\t"; temp2=NextDate(temp1); } else{ fout << temp1 << "\t"; if (temp2==temp1) { fout << "正确"; } else{ fout << "错误"; } fout << "\r\n"; } i++; } fin.close(); fout.close(); } int main(int argc, const char * argv[]) { driver(); return 0; }