I have a program where I need to read the date being entered. I am able to read the date correctly if the date is entered D/MM/YYYY. When ever a date is entered as DD/MM/YYYY it reads incorrectly because the substr isn't accounting for days that has 2 digits in it .
so there are 4 different correct ways dates can be entered:
D/M/YYYY
DD/MM/YYYY
D/MM/YYYY
DD/M/YYYY
Furthermore, if an incorrect day/month is entered such as 100/4/2018 it hinders reading the rest of the string correctly. The year and month.
Through my own testing I had a for loop looking for the first "/" then reading what came before it but that didn't work.
How can I account for these different ways of entering dates?
MYDate::MYDate(std::string date) {
//int size = date.length();
SetYear(year_ = std::atoi(date.substr(5, 4).c_str()));
SetMonth(month_ = std::atoi(date.substr(3, 2).c_str()));
SetDay(day_ = std::atoi(date.substr(0, 2).c_str()));
/*
9/9/2001
09/09/2001
9/09/2001
09/9/2001
*/
}
You may just use an istringstream to some simple parsing if you replace the '/'. Like this:
std::replace( date.begin(), date.end(), '/', ' ');
std::istringstream stream(date);
stream >> day_;
stream >> month_;
stream >> year_;