簡體   English   中英

Borland C ++ Builder中的scanf

[英]scanf in Borland C++ Builder

我正在嘗試使用scanf函數檢查變量的類型。 它對於Dev C ++很好用(我的輸入是int),但沒有使用Borland。 這是我嘗試過的:

AnsiString as = Edit1->Text;
string b = as.c_str();

int testb = atoi(b.c_str());

if(scanf("%i", &testb)==1){
do sth;
}

有任何想法嗎?

[edit1]從Spektre的評論中移出

我還有另一個問題。 我的輸入值應類似於xx-xx-xxxx所以它是一個日期。
我必須檢查天,月和年是否為整數。
我這樣嘗試過:

AnsiString a = Edit1->Text;
date = a.c_str();
 if (a==AnsiString().sprintf("%i",atoi(a.SubString(0,2).c_str()))
  && a==AnsiString().sprintf("%i",atoi(a.SubString(3,2).c_str()))
  && a==AnsiString().sprintf("%i",atoi(a.SubString(6,4).c_str())) )
 { 
 //do sth
 }
  • 但它只檢查一天。 有人知道為什么嗎? – JB 20小時前

您正在使這一過程變得比原本應有的復雜得多。

scanf()從STDIN讀取,但是GUI進程不使用STDIN進行輸入,這就是為什么它對您不起作用的原因。 使用sscanf()代替:

int testb;
if (sscanf(AnsiString(Edit1->Text).c_str(), "%d", &testb) == 1)
{
    // do sth ...
}

或者,可以使用RTL的TryStrToInt()代替:

int testb;
if (TryStrToInt(Edit1->Text, testb))
{
    // do sth ...
}

至於檢查日期字符串,可以為此使用sscanf()

int day, month, year;
if (sscanf(AnsiString(Edit1->Text).c_str(), "%2d-%2d-%4d", &day, &month, &year) == 3)
{
    // do sth ...
}

或使用RTL的TryStrToDate()

TDateTime testb;

TFormatSettings fmt = TFormatSettings::Create();
fmt.DateSeparator = '-';
fmt.ShortDateFormat = "d-m-y";

if (TryStrToDate(Edit1->Text, testb, fmt))
{
    // do sth ...
}

我是這樣做的

AnsiString s=Edit1->Text; // copy to real AnsiString ... the AnsiStrings inside visual components are not the same ... some functions/operations does not work properly for them
int e,i,l=s.Length();

for(e=0,i=1;i<=l;) 
 {
 e=1; // assume it is integer
 if (s[i]=='-') i++; // skip first minus sign
  for (;i<=l;i++) // scan all the rest 
   if ((s[i]<'0')||(s[i]>'9')) // if not a digit
    { 
    e=0; // then not an integer
    break; // stop
    }
 break;
 }
// here e holds true/false if s is valid integer

now you can use safely
if (e) i=s.ToInt(); else i=0;
  • 不確定s.ToInt()是否也是如此,但至少直到BDS2006
  • 如果調用s.ToDouble()以獲取無效數字,則將引發不可屏蔽的異常
  • 因此,例如,如果您嘗試轉換0.98且小數點未設置為. 您的程序崩潰(atoi和atof是安全的)

您還可以使用sprintf:

AnsiString s=Edit1->Text;
if (s==AnsiString().sprintf("%i",atoi(s.c_str()))) /* valid integer */;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM