Shouldn't have spoon fed you...
Code:#include <iostream> #include <exception> #include <string> struct Date { unsigned int month; unsigned int day; }; Date GetDateFromString (const std::string& dateString) { Date date = {0, 0}; char buff[2]; // Check for the correct format... if (dateString.length() != 5) throw ("The date string must be 5 characters long."); size_t slashPos = dateString.find_first_of ('/'); if (slashPos == std::string::npos) throw ("Error parsing date. No slash was found."); else if (slashPos != 2) throw ("Error parsing date. The slash is not positioned correctly."); // Convert from string to integer dateString.copy (buff, 2); date.month = atoi (buff); if (date.month == 0) throw ("Error parsing date. Incorrect number provided for month"); dateString.copy (buff, 2, 3); date.day = atoi (buff); if (date.day == 0) throw ("Error parsing date. Incorrect number provided for day"); return date; } int main () { std::string dateString; Date date; try { std::cout << "Please enter the month and day (mm/dd): "; std::cin >> dateString; Date date = GetDateFromString (dateString); std::cout << "Month: " << date.month << std::endl; std::cout << "Day: " << date.day << std::endl; } catch (const char * exception) { std::cout << exception << std::endl; return -1; } return 0; }




Reply With Quote