读书人

怎样在C语言中动态显示时间,该怎么处理

发布时间: 2012-06-06 16:44:11 作者: rapoo

怎样在C语言中动态显示时间
这是一个显示电脑当前时间的程序,怎么能让它“动”起来呢?即不断刷新,像电子手表一样显示最新时间.
#include <stdio.h>
#include <string.h>
#include <time.h>

int Show(void)
{
char str[100];
time_t t;
struct tm *lt;
t = time(NULL);
lt = localtime(&t);
strftime(str,100,"%Y-%m-%d %H:%M:%S ",lt);
printf("当前日期及时间是:\n%s\n",str);
getch();
return 0;
}

main()
{
Show();
}

[解决办法]

C/C++ code
#include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h>int Show(void) {   char str[100];   time_t t;   struct tm *lt;   t = time(NULL);   lt = localtime(&t);   strftime(str,100,"%Y-%m-%d  %H:%M:%S ",lt);   printf("当前日期及时间是:\n%s\n",str);    return 0; } void sleep( clock_t wait ){   clock_t goal;   goal = wait + clock();   while( goal > clock() )      ;}main() {         while(true)    {    system("cls");    Show();    sleep(1000);    }}
[解决办法]
C/C++ code
 
/********************************************
**
** Windows XP sp2, Micrsoft Visual C++ 6.0
** myDate.c
**
**********************************************/


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include <windows.h>

typedef struct
{
int year;
int month;
int day;
int hour;
int minute;
int second;
int week;
}myDate;

int leap(int year)
{
if (year%4 == 0 && year%100 !=0 || year%400 == 0)
{
return 1;
}
return 0;
}

int main()
{
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char * weekday[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
time_t t = time(NULL);
struct tm *cur = localtime(&t);

myDate Date = {cur->tm_year+1900, cur->tm_mon + 1, cur->tm_mday, cur->tm_hour, cur->tm_min, cur->tm_sec, cur->tm_wday};

printf("%4d年%02d月%02d日[%s]%02d时%02d分%02d秒\r", Date.year, Date.month, Date.day, weekday[Date.week], Date.hour, Date.minute, Date.second);

while(1)
{
Sleep(1000);
days[2] = (leap(Date.year) ? 28:29);

Date.second++;
if ( Date.second == 60)
{
Date.second = 0;
Date.minute++;

}

if (Date.minute == 60)
{
Date.minute = 0;
Date.hour++;
}

if (Date.hour == 24)
{
Date.hour = 0;
Date.week = (++Date.week)%7;
Date.day++;
}


if (Date.day == (days[Date.month] + 1))


{
Date.day = 1;
Date.month++;
}

if (Date.month == 13)
{
Date.month = 1;
Date.year++;
}

printf("%4d年%02d月%02d日[%s]%02d时%02d分%02d秒\r", Date.year, Date.month, Date.day, weekday[Date.week], Date.hour, Date.minute, Date.second);
}

return 0;
}



[解决办法]
C/C++ code
#include <time.h>#include <stdio.h>int main(){ time_t lt; for(;!kbhit();) {  lt=time(NULL);  printf(ctime(&lt));  delay(10000);  clrscr();  }  return 0; }
[解决办法]
C/C++ code
#include <time.h>int main(){time_t t; struct tm *lt; for(;!kbhit();) {time(&t);  lt=localtime(&t);  printf("%d-%d-%d\n",1900+lt->tm_year,lt->tm_mon,lt->tm_mday);  printf("%d.%d.%d",lt->tm_hour,lt->tm_min,lt->tm_sec);  delay(10000);  system("cls"); } return 0;} 

读书人网 >C语言

热点推荐