Validation of user input ( month/day)
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Validation of user input ( month/day)

  1. #1
    Join Date
    Feb 2008
    Posts
    1

    Validation of user input ( month/day)

    User has to input date in mm/dd format, anything else creates error:
    Code:
    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?
    Last edited by EmilKh; February 15th, 2008 at 08:02 PM.

  2. #2
    Join Date
    Aug 2007
    Location
    127.0.0.1
    Posts
    20

    Re: Validation of user input ( month/day)

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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center