C - Read Formatted Time Once through Scanf in C Language

In this code snippet we are going to learn how can we read formatted values through scanf() in c, this example will demonstrate you to read formatted time in HH:MM:SS format using scanf().

Generally, we cannot read anything between the integer values using scanf() function, for example - if we want to provide 3 values together either we have to give space or enter to separate them.

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.

For example: If we want to enter time (hours, minutes and seconds) without using any kind of scanf() formatting, we need to enter values like this:

    1) Separating by spaces 
    
    Enter time: 12 50 59

    2) Separating by return key (ENTER)
    
    Enter time: 12 
    50 
    59

We can also separate them by special characters, for example - if we want to input time separating them colons (:) we can do it by using placing colon : between two format specifiers.

Consider the given statement,

 scanf("%02d:%02d:%02d",&hour,&minute,&second);

This statement will take input of three values and they all must be separated by the colons :

Example:

    Enter time (in HH:MM:SS) 12:50:59
    Entered time is  12:50:59

Read Formatted Time (in HH:MM:SS format) through Scanf() in C

/*C - Read Formatted Time Once through Scanf in C Language.*/
 
#include <stdio.h>
 
int main(){
    int hour,minute,second;
     
    printf("Enter time (in HH:MM:SS) ");
    scanf("%02d:%02d:%02d",&hour,&minute,&second);
     
    printf("Entered time is  %02d:%02d:%02d\n",hour, minute, second);
     
    return 0;   
}

Output

Enter time (in HH:MM:SS) 12:50:59
Entered time is  12:50:59

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.