C program to read time in string format and extract hours, minutes and second also check time validity
Given time in string format (HH:MM:SS) and we have to extract time in hours, minutes and seconds, we are also checking whether given time is valid or not using C program.
Here, to read time - we are using fgets() function, which can also be used to read the string, this function has three parameters,
Syntax:
char *fgets(char *string, int N, stdin)
Here,
- string - character array to store the input value
- N - maximum number of character to read
- stdin - a pointer to a file stream, from where we are reading the string (input source)
There is a function ValidateTime ()- which we designed to check whether given time is valid or not, it will return 1, if time is not valid, else it will return 0.
Use of sscanf()
To extract the integer values from formatted string, we can use sscanf() function, which scans (reads) values from the formatted string.
Consider the statement,
sscanf(string , "%d:%d:%d" , &hour,&min,&sec);
Here, values will be scanned and assigned to hour, minute and sec variables.
Example:
Input:
Enter the time in "hh:mm:ss" format : "10:20:30"
Output:
The Time is : 10:20:30
Input:
Enter the time in "hh:mm:ss" format : "25:20:30"
Output:
The Time is : Invalid Time. Try Again.
Program to extract hours, minutes and seconds from the string in C
Output
need an explanation for this answer? contact us directly to get an explanation for this answer