Click to See Complete Forum and Search --> : Validation of user input ( month/day)


EmilKh
February 15th, 2008, 07:59 PM
User has to input date in mm/dd format, anything else creates error:

cout << "Please enter the month and day (mm/dd) >> ";
cin.getline(buffer, 80);

if (strpbrk("/", buffer))
{
month = atoi ( strtok(buffer, "/") );
if (NULL)
day = atoi (strtok(NULL, "\n") );
}

if (month < 1 || month > 12 || day < 1 || day > 31)
cout << buffer << " is not a valid date.";


It's working in 99.99% cases. 0.01% is input like "/", which screws me up and "Bus error" appears. Any ideas?

aLiNuSh
February 16th, 2008, 02:01 PM
Shouldn't have spoon fed you...


#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;
}