谢谢各位老大的建议,水越淌越深咯。

梅尚程荀
马谭杨奚
程序代码:
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <conio.h>
#define K_ENTER 0x0D
// 用法:InputString 是接收的字符串數組用於返回,Seconds 是限時秒數,輸入時按Enter鍵結束
bool GetString(char InputString[], unsigned long int Seconds);
void main(void)
{
char Buffer[1024];
GetString(Buffer, 5UL); // 測試限5秒
printf_s("\nInput string is: %s\n", Buffer); // 輸出接收的字符串,如果超時為空串
_getch();
}
bool GetString(char InputString[], unsigned long int Seconds)
{
time_t Start; // 開始時間
time_t End; // 結束時間
int Character = '\0'; // 輸入的字符
unsigned int Counter = 0; // 字符計數器
bool Success = true;
time(&Start);
do
{
time(&End);
if (End - Start >= Seconds)
{
Success = false;
Counter = 0;
break;
}
if (_kbhit())
{
Character = _getch();
if (isprint(Character) && (Character != K_ENTER))
{
InputString[Counter++] = Character; // 本例匆忙,沒寫字符計數超界檢查代碼,安全代碼必須寫上
_putch(Character);
}
}
} while(Character != K_ENTER);
InputString[Counter] = '\0';
return Success;
}

程序代码:
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <conio.h>
#define K_ENTER 0x0D
bool GetString(char InputString[], size_t Length, unsigned long int Seconds);
void main(void)
{
char Buffer[6];
printf_s("Please type a string, max %d characters, Press Enter to confirm: ", sizeof(Buffer) - 1);
GetString(Buffer, sizeof(Buffer) - 1, 5UL);
printf_s("\nYour input is: %s\n", Buffer);
_getch();
}
bool GetString(char InputString[], size_t Length, unsigned long int Seconds)
{
time_t Start; // 開始時間
time_t End; // 結束時間
int Character = '\0'; // 輸入的字符
size_t Counter = 0; // 字符計數器
bool Success = true;
if (Length < 1) // 只容納一個字符的字符串直接返回空串,並報告輸入失敗
{
InputString[0] = '\0';
return false;
}
time(&Start);
do
{
time(&End);
if (End - Start >= Seconds)
{
Success = false;
Counter = 0; // 如果需要超時保留已輸入的字符串,則此處不要歸零
break;
}
if (_kbhit())
{
Character = _getch();
if (Character == 0xE0)
{
// 沒收控制鍵,諸如BackSpace、Delete、TAB、光標鍵等均不接受
_getch();
continue;
}
if (isprint(Character) && (Character != K_ENTER))
{
// 本代碼全程使用ANSI版本的函數,isprint()是排斥中文字符的,因此若要輸入中文,不使用isprint()即可,但
// 要檢測中文字符,對應Counter += 2(與系統的編碼體系有關),否則有字符串溢出危險。改用寬字符版本函數
// 可有效避免此種麻煩。
InputString[Counter++] = Character;
_putch(Character);
}
}
} while((Character != K_ENTER) && (Counter < Length));
InputString[Counter] = '\0';
return Success;
}



