Time Validity Checker

This C program prompts the user to enter a time in HH:MM:SS format and checks if the input is valid. It continues to ask the user until they choose to stop. Input is validated for correct format and range for hours, minutes, and seconds, providing appropriate feedback for each input.
mail@pastecode.io avatar
unknown
c_cpp
19 days ago
890 B
2
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int firstNum, secondNum, thirdNum;
    char choice;
    int result;

   do {
     printf("Enter number in the form of HH:MM:SS : ");
    result = scanf("%d:%d:%d", &firstNum, &secondNum, &thirdNum);

      // Check if the scanf successfully parsed 3 integers
    if (result == 3) {
        // Validate if the time is correct
        if (firstNum >= 0 && firstNum <= 23 &&
            secondNum >= 0 && secondNum <= 59 &&
            thirdNum >= 0 && thirdNum <= 59) {
            printf("Valid Time\n");
        } else {
            printf("Invalid Time\n");
        }
    } else {
        // Handle invalid input format
        printf("Invalid Input Format\n");
    }

    printf("\n");
    printf("Try again? (y/n): ");
    scanf(" %c", &choice);

   } while (choice == 'Y' || choice == 'y');

   printf("=> End");

    return 0;
}
Leave a Comment