A. Write C code to create a structure called time_of_day, which stores the current time in hours, minutes, and seconds. All the fields should be integers except for seconds, which should be a floating point value.
B. Write a C function called check_time, which takes a pointer to a time_of_day structure as input, and return 1 if the time is valid (0 to 23 hours, 0 to 59 minutes, 0 to 59.999999 seconds) and 0 otherwise. Assume that times are stored in 24 hour format, with 00:00:00 being midnight and 23:59:59.9999 being the last millisecond of the day.
C. Write a main program which reads a time from the user in the normal hh:mm:ss.sss format and stores it in a time_of_day structure. Your program should then call the check_time function to determine if it is a valid time or not, and display "valid time" or "invalid time" to the screen.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct time{
int hr;
int min;
double sec;
}time;
int check_time(time t)
{
if((t.hr>=0 && t.hr<=23) && (t.min>=0 && t.min<=59) && (t.sec>=0.0 && t.sec<60.0))
return 1;
else
return 0;
}
int main()
{
time t;
printf("Enter time : hh:mm:ss.sss\n");
char c[30],h[10];
scanf("%s",c);
int i;
for(i=0;c[i]!=':';i++)
{
strncat(h,c+i,1);
}
t.hr=atoi(h);
h[0]=0;
for(i=i+1;c[i]!=':';i++)
{
strncat(h,c+i,1);
}
t.min=atoi(h);
h[0]=0;
for(i=i+1;c[i]!='\0';i++)
{
strncat(h,c+i,1);
}
t.sec=atof(h);
if(check_time(t))printf("valid time\n");
else
{
printf("invalid time\n");
}
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.