Search code examples
cvalidationtimeformatuser-input

check if user input according to the format


I have a system where the user key in the check in time and check out time in a HH:MM format (code below)

//category input here
printf("Check in time (HH:MM 24H FORMAT): ");
scanf("%d:%d",&hour,&minute);
printf("Check out time (HH:MM 24H FORMAT): ");
scanf("%d:%d",&hour2,&minute2);

how can i validate the user input according to the format so that such error wont happen (example below)

//example one
category: 2
Check in time (HH:MM 24H FORMAT): 1
Check out time (HH:MM 24H FORMAT): 3

Driver has to pay: $2

//example 2
category: 1
Check in time (HH:MM 24H FORMAT): -1
Check out time (HH:MM 24H FORMAT): 0

Driver has to pay: $1

i've tried

else if (hour >= 24 || hour2 >= 24 || hour < 0 || hour2 < 0){
    printf("\nERROR! HOUR SHOULD NOT BE 24 OR EXCEED 24 OR LESS THAN 0\n");
}

other than that, i have no idea or solution on how to check whether the user is using the correct format :(

thanks in advance for the help


Solution

  • Consider reading a line of user input with fgets().

    Then parse the input string with sscanf() with a trailing "%n" to record scanning offset - if scanning went that far.

    Then followup with range comparisons.

    char buf[100];
    if (fgets(buf, sizeof buf, stdin)) {
      int n = 0;
      sscanf(buf, "%d :%d %n", &hour,&minute, &n);
      if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 && hour < 24) {
        Success(); // OP's custom code here
      } else {
        Failure(); // OP's custom code here 
      }
    }
    

    To allow "24:00" change compare to

      if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 && 
          (hour*60 + minute <= 24*60)) {
    

    To check for exactly 5 characters and \n:

      sscanf(buf, "%*1[0-2]%*1[0-9]:%*1[0-5]%*1[0-9]%*[\n]%n", &n);
      if (n == 6) {
        // partial success, now re-scan with "%d:%d" and check positive ranges.