Read formatted time through scanf()

C program to read formatted time (in HH:MM:SS format) through scanf().

Program

#include<stdio.h>
#include<conio.h>
void main()
{
    int hour, min, sec;

    printf("Enter time (in HH:MM:SS)\t:");
    scanf("%d:%d:%d",&hour,&min,&sec);

    printf("\nEntered time is  %d:%d:%d\n",hour, min, sec);
    getch();
}

Output

Enter time (in HH:MM:SS)        :23:45:34

Entered time is  23:45:34

Explanation

In this program, we will see the extended functionality of scanf(). Generally, we cannot read anything between the integer values using scanf(). For example, if we want to provide 3 values together either we have to give space or enter to separate them.

If we want to enter time (hours, minutes and seconds) without using any kind of scanf() formatting, we need to enter values like this:
  • Separated by spaces
  • Enter time: 12 50 59
  • Separated by return key (ENTER)
  • Enter time: 12
    50
    59

    But, scanf() also provide some characters that can be placed between the format specifiers, which will separate the given input matching with the same characters and store the values in corresponding variables.

    In above example, if we want to input time, separated by colons (:), we can do it by placing colon : between two format specifiers.
    scanf("%d:%d:%d",&hour,&min,&sec);
    This statement will take input of three values and they all must be separated by the colons :

    Example:
    Enter time (in HH:MM:SS) :23:45:34
    Entered time is 23:45:34