How to check a specific format of string in C -


i have following code accepts string resembles hours.. want check if string format xx-yy xx resembles hour yy.. code worked fine when input "02-13-" returns true want return false cause it's not correct (cause has - @ end)

bool hourisvalid(char * hours) {   int openh = 0;   int closeh = 0;    if ((sscanf(hours, "%d-%d", & openh, & closeh) == 2) && openh >= 0 && openh <= 24 && closeh >= 0 && closeh <= 24) {     if (openh >= closeh) {       return false;     }     return true;   } else {     return false;   } } 

the solution depends on how "pedantic" code has when deciding if input valid or not. example, might expect "2-14", "02 - 15", " 2-14 " valid, or might not. depends.

if want pedantic version accepts exact format "dd-dd" no leading or trailing characters or white spaces , two-digit format each hour value, check string follows before reading in values sscanf-code:

if (strlen(hours) != 5)     return 0;  if (hours[2] != '-')     return 0;  if ( !isdigit(hours[0])     || !isdigit(hours[1])     || !isdigit(hours[3])     || !isdigit(hours[4])     )     return 0; 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -