开发者

How to do Keypress Validation in a Delphi 7 Console Application

I am creating a simple delphi console app which does arithmetic operations of the number entered by user, problem is that the user can enter 'a'..'z','A'..'Z' which leads开发者_如何学Python to app crash. How can i prevent this? Using try-except does not work, anybody has ideas on preventing this crash?

Here is my code:

 Write('Please Enter a Number:=');
Readln(str1);
try
  num1:=StrToFloat(str1);
except
on e:exception do
  Writeln(e.message);
end;

Thanks in Advance.


As David, points out, exceptions work just as fine in console apps as they do in GUI apps. For instance, this works flawlessly:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  s: string;
  f1, f2: extended;

begin

  try

    Writeln('Please enter a number:');
    Readln(s);
    f1 := StrToFloat(s);

    Writeln('Please enter a second number:');
    Readln(s);
    f2 := StrToFloat(s);

    Writeln('The sum is ', FloatToStr(f1+f2));
    Readln;

  except
    on E: Exception do
    begin
      Writeln(E.Message);
      Readln;
    end;
  end;

end.

An alternative not using exceptions is to use the TryStrToFloat function:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  s1, s2: string;
  f1, f2: extended;

begin

  Writeln('Please enter a number:');
  Readln(s1);
  Writeln('Please enter a second number:');
  Readln(s2);

  if TryStrToFloat(s1, f1) and TryStrToFloat(s2, f2) then
    Writeln('The sum is ', FloatToStr(f1 + f2))
  else
    Writeln('Invalid input.');

  Readln;

end.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜