德尔福编辑文本整数:减号错误



嗨,我对德尔福来说是初学者。但让我困惑的是我有 编辑1.文本和变量"i",它使用StrToInt(Edit1.Text);一切都很好,直到我输入减号

如果我复制/粘贴带有数字的减号(例如 -2),它可以工作谁能帮我!问候,奥马尔

当您不能 100% 确定输入字符串是否可以转换为整数值时,使用 StrToInt 转换函数是不安全的。编辑框就是这样一个不安全的情况。转换失败,因为您输入了无法转换为整数的-符号作为第一个字符。清除编辑框时,也会发生同样的情况。为确保此转换安全,您可以使用 TryStrToInt 函数,该函数会为您处理转换异常。您可以通过以下方式使用它:

procedure TForm1.Edit1Change(Sender: TObject);
var
  I: Integer;
begin
  // if this function call returns True, the conversion succeeded;
  // when False, the input string couldn't be converted to integer
  if TryStrToInt(Edit1.Text, I) then
  begin
    // the conversion succeeded, so you can work
    // with the I variable here as you need
    I := I + 1;
    ShowMessage('Entered value incremented by 1 equals to: ' + IntToStr(I));
  end;
end;

显然,您会收到一个错误,因为-不是整数。您可以改用 TryStrToInt。

最新更新