2013年5月8日 星期三

(C++) 輸入字串控制 - 數字篇

如果有一個地方可以讓使用者輸入,而且限制只能輸入數字型態,數字型態包括了正負數及小數,可以參考以下方法:

當使用者每件入一個按鍵,就呼叫此function:

void __fastcall OnEditPress(TObject *Sender, wchar_t &Key)
{
 std::wstring numerics(L"0123456789");
 TEdit *EditExit = (TEdit*)Sender;
 std::wstring editString = EditExit->Text.c_str();

 if((Key < L'0' || Key > L'9') && Key != L'\b' && Key != L'.' && Key != L'-')
 {
  Key = 0;
  return;
 }
 // avoid ".3"
 bool pointErrorUsing = (editString.find_first_of(L'.') != std::wstring::npos)
       || (editString.find_first_of(numerics) == std::wstring::npos);
 if(Key == L'.' && pointErrorUsing)
 {
  Key = 0;
  return;
 }
 // avoid ex: "-2-3" and "2-34"
 bool minusErrorUsing = (editString.find_first_of(L'-') != std::wstring::npos)
       || !editString.empty();
 if(Key == L'-' && minusErrorUsing)
 {
  Key = 0;
  return;
    }
 if(EditExit->Text.Length() > 5 && Key != L'\b')
 {
  Key = 0;
  return;
 }
 DoChange(Sender);
}

沒有留言:

張貼留言