Home »
C programs »
C string programs
C program to read time in string format and extract hours, minutes and second also check time validity
In this C program, we are going to read time in string forma (the specified time format will be HH:MM:SS) and program will extract the hours, minutes and seconds also checking time validity.
Submitted by IncludeHelp, on April 10, 2018
Problem statement
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.
Reading time in string format
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
/** C program to fetch the values of hours,
* minutes and seconds from the string and
* print it using integer variables
*/
#include <stdio.h>
// function to validate the time
int ValidateTime(int hh , int mm , int ss)
{
int ret=0;
if(hh>24) ret=1;
if(mm>60) ret=1;
if(ss>60) ret=1;
return ret;
}
// main function
int main()
{
// declare a char buffer
char string[100]={0};
// declare some local int variables
int ret=0,hour=0,min=0,sec=0;
printf("\nEnter the time in \"hh:mm:ss\" format : ");
fgets(string,100,stdin);
// fetch the hour,min and sec values from the
// string and then store it in int variables
// in order to validate them
sscanf(string , "%d:%d:%d" , &hour,&min,&sec);
//printf("\nHH : %d MM : %d SS : %d",hour,min,sec);
// validate the time
ret = ValidateTime(hour,min,sec);
if(ret)
{
printf("\nInvalid Time. Try Again.\n");
}
else
{
printf("\nThe Time is : %d:%d:%d\n",hour,min,sec);
}
return 0;
}
Output
Run 1 :
Enter the time in "hh:mm:ss" format : 10:20:30
The Time is : 10:20:30
Run 2 :
Enter the time in "hh:mm:ss" format : 25:20:30
Invalid Time. Try Again.
Run 3:
Enter the time in "hh:mm:ss" format : 10:61:30
Invalid Time. Try Again.
C String Programs »