我正在制作一个小文件阅读和数据验证程序,作为我的TAFE(大专院校)课程的一部分,这包括检查和验证日期.
我决定最好用一个单独的类来完成,而不是将它集成到我的主驱动程序类中.
问题是我的测试程序运行后出现了分段错误(核心转储).我可以说,在程序终止时发生错误,在调用析构函数后弹出.到目前为止,我没有找到这个错误的原因,并且希望一些开明的灵魂可能向我展示我的方式的错误.
date.h
#ifndef DATE_H #define DATE_H #include <string> using std::string; #include <sstream> using std::stringstream; #include <cstdlib> using std::exit; #include <iostream> using std::cout; using std::endl; class date { public: explicit date(); ~date(); bool before(string dateIn1,string dateIn2); int yearsBetween(string dateIn1,string dateIn2); bool isValid(string dateIn); bool getDate(int date[],string dateIn); bool isLeapYear(int year); private: int days[]; }; #endif
date.cpp
#include "date.h" date::date() { days[0] = 31; days[1] = 28; days[2] = 31; days[3] = 30; days[4] = 31; days[5] = 30; days[6] = 31; days[7] = 31; days[8] = 30; days[9] = 31; days[10] = 30; days[11] = 31; } bool date::before(string dateIn1,string dateIn2) { int date1[3]; int date2[3]; getDate(date1,dateIn1); getDate(date2,dateIn2); if (date1[2] < date2[2]) { return true; } else if (date1[1] < date2[1]) { return true; } else if (date1[0] < date2[0]) { return true; } return false; } date::~date() { cout << "this is for testing only,plox delete\n"; } int date::yearsBetween(string dateIn1,dateIn2); int years = date2[2] - date1[2]; if (date1[1] > date2[1]) { years--; } if ((date1[1] == date2[1]) && (date1[0] > date2[1])) { years--; } return years; } bool date::isValid(string dateIn) { int date[3]; if (getDate(date,dateIn)) { if (date[1] <= 12) { int extraDay = 0; if (isLeapYear(date[2])) { extraDay++; } if ((date[0] + extraDay) <= days[date[1] - 1]) { return true; } } } else { return false; } } bool date::getDate(int date[],string dateIn) { string part1,part2,part3; size_t whereIs,lastFound; whereIs = dateIn.find("/"); part1 = dateIn.substr(0,whereIs); lastFound = whereIs + 1; whereIs = dateIn.find("/",lastFound); part2 = dateIn.substr(lastFound,whereIs - lastFound); lastFound = whereIs + 1; part3 = dateIn.substr(lastFound,4); stringstream p1(part1); stringstream p2(part2); stringstream p3(part3); if (p1 >> date[0]) { if (p2>>date[1]) { return (p3>>date[2]); } else { return false; } return false; } } bool date::isLeapYear(int year) { return ((year % 4) == 0); }
最后,测试程序
#include <iostream> using std::cout; using std::endl; #include "date.h" int main() { date d; cout << "1/1/1988 before 3/5/1990 [" << d.before("1/1/1988","3/5/1990") << "]\n1/1/1988 before 1/1/1970 [" << d.before("a/a/1988","1/1/1970") <<"]\n"; cout << "years between 1/1/1988 and 1/1/1998 [" << d.yearsBetween("1/1/1988","1/1/1998") << "]\n"; cout << "is 1/1/1988 valid [" << d.isValid("1/1/1988") << "]\n" << "is 2/13/1988 valid [" << d.isValid("2/13/1988") << "]\n" << "is 32/12/1988 valid [" << d.isValid("32/12/1988") << "]\n"; cout << "blerg\n"; }
我留下了一些无关的cout语句,我一直在尝试找出错误.
我提前谢谢你.
解决方法
更改:
private: int days[];
至:
private: int days[12];