akohan
asked on
Wrong results in C
Hi Group,
I'm running the following code in snippet. However, I get wrong number as output. I will appreciate it if you help me to find where I went wrong.
Thanks,
ak
Results:
tmp]$ ./ut
Enter the time (hh:mm:ss):1
Updated time is 134513817:1321973877:-1077 819540
I'm running the following code in snippet. However, I get wrong number as output. I will appreciate it if you help me to find where I went wrong.
Thanks,
ak
Results:
tmp]$ ./ut
Enter the time (hh:mm:ss):1
Updated time is 134513817:1321973877:-1077
#include <stdio.h>
struct time
{
int hr;
int min;
int sec;
};
struct time timeUpdate(struct time now);
int main(void)
{
struct time currentTime, nextTime;
printf("Enter the time (hh:mm:ss):");
scanf("%i:%i:%i", ¤tTime.hr,
¤tTime.min,
¤tTime.sec
);
nextTime = timeUpdate(currentTime);
printf("Updated time is %.2i:%.2i:%.2i\n", nextTime.hr, nextTime.min, nextTime.sec);
return 0;
}
struct time timeUpdate(struct time now)
{
++now.sec;
if (now.sec == 60 ){
now.sec = 0;
++now.min;
if (now.min == 60 ){
now.min = 0;
++now.hr;
if (now.hr == 24)
now.hr = 0;
}
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
the time function returns the number of seconds since the 1st january 1970.
Try this instead to get local time
(code example pasted from http://www.cplusplus.com/reference/clibrary/ctime/localtime.html)
Try this instead to get local time
(code example pasted from http://www.cplusplus.com/reference/clibrary/ctime/localtime.html)
/* localtime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Also, here are the details for the tm struct so you can take any part of the tiem you like from it
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you so much!
I totally had missed that line. One thing about timing in C; what should I do to get only the second part. What I'm trying to say is that let's assume you want to get the value from your machine's clock and extract the second part of it.
What should I do then?
I tried this code:
{
time_t seconds;
seconds = time (NULL);
printf("%d ", seconds);
}
when I print it continously it shows the increasing value which I can guess it is from clock but the number is so big:
1202774451
1202774452
1202774453
Any idea?
regards,
ak