標籤:c語言
<strong><span style="font-size:14px;">C語言 -- 定時關機程式</span></strong>
<strong></strong><span style="font-size:14px;"></span>
<strong><span style="font-size:14px;">特別注意:</span></strong>
<strong><span style="font-size:14px;"> 1.從接收到的char * 類型轉換為 int ,一定不能使用(int)這種方式來轉換,要用atoi()</span></strong>
<strong><span style="font-size:14px;"> 使用方式:原型: int atoi(const char *nptr);</span></strong>
<strong><span style="font-size:14px;">2. 多個字串合并,使用sprintf()</span></strong>
<strong><span style="font-size:14px;"> 使用方式:sprintf(char *buffer,const char * format[,argument,...])</span></strong>
<strong><span style="font-size:14px;"> 以下有使用方式</span></strong>
<strong><span style="font-size:14px;"></span></strong>
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <ctype.h>#include <time.h> int isNumber(char *a);void getCurrentDate(int seconds); int main(){printf("歡迎進入定時關機系統!\n");getCurrentDate(0);char str[2]; char flag = 1;while(flag){printf("輸入A定時關機,輸入C取消定時關機\n"); gets(str);if(strcmp(str,"a")==0) { printf("請輸入時間的秒數:\n");char seconds[10];while(1){ gets(seconds); if(isNumber((char*)seconds))break;else{printf("輸入的秒數不正確,請重新給輸入!\n");continue;}} int temp_seconds = atoi(seconds);getCurrentDate(temp_seconds);char shutdown[50] = "shutdown -s -t ";strcat(shutdown,seconds);system(shutdown);system("pause");break;} else if(strcmp(str,"C")==0 || strcmp(str,"c")==0) {system("shutdown -a");printf("已經取消定時關機\n");system("pause");break;}else{printf("輸入的值不正確,請重新輸入!\n"); flag=1;}}return 0;}//判斷字串是否是數字int isNumber(char *a){char flag=1;int len = strlen(a);for(int i=0;i<len;i++){if(isdigit(a[i])==0){flag = 0;break;}}if(flag) return 1;elsereturn 0;} //擷取系統目前時間void getCurrentDate(int seconds){time_t rawtime;struct tm *timeinfo,*timeinfo2;time(&rawtime); if(seconds > 0){rawtime += seconds; }timeinfo = localtime(&rawtime); int year = timeinfo->tm_year + 1900; int month = timeinfo->tm_mon+1; int day = timeinfo->tm_mday; int hour = timeinfo->tm_hour; int min = timeinfo->tm_min; int secs = timeinfo->tm_sec; char *str = (char*)malloc(sizeof(char)*100); memset(str,0,100);//多個值合并字串if(seconds > 0){sprintf(str,"在%d年%d月%d日 %d時%d分%d秒後關機...",year,month,day,hour,min,secs); }else{sprintf(str,"現在時間是:%d年%d月%d日 %d時%d分%d秒 ",year,month,day,hour,min,secs); } puts(str);free(str);}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
C語言 -- 定時關機程式