Question 6
Back to Exercise
Check whether strings such as "23:59:59" are valid 24-hour times.
Solution
#include <stdbool.h>
#include <stdio.h>
bool valid_time(const char *s) {
int h, m, sec;
char extra;
if (sscanf(s, "%2d:%2d:%2d%c", &h, &m, &sec, &extra) != 3) /* exactly three numbers, nothing after */
return false;
return h >= 0 && h <= 23 && m >= 0 && m <= 59 && sec >= 0 && sec <= 59;
}
int main(void) {
const char *tests[] = {"23:59:59", "24:00:00", "12:60:00", "09:05:07", "7:30"};
for (int i = 0; i < 5; i++)
printf("%-9s %s\n", tests[i], valid_time(tests[i]) ? "valid" : "invalid");
return 0;
}
23:59:59 valid 24:00:00 invalid 12:60:00 invalid 09:05:07 valid 7:30 invalid
The extra %c catches trailing junk: if anything follows the seconds, sscanf returns 4 instead of 3. Then six range checks joined by && validate each field.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!