Sign in to follow this  
xyuri

Delphi type checking?

Recommended Posts

I'm doing an assignment and as you can guess its due pretty soon and dont have some to ask the lecturer how to do this AGAIN ... I asked him last lesson and no matter how much I argued that the SrtToInt would completely crash the app is the string was not numeric, he reconed it would work?! Could someone please help me out with just this? I need to check if a string is all numeric or not. Any help is appreciated. Thanks.

Share this post


Link to post
Share on other sites
StrToInt will raise an exception (which you can catch) if it's not a valid integer. However using exceptions for basic input checking is not good programming practice [from a code or performance standpoint] (only Java resorts to this). StrToInt (with it's exceptions) should really only be used when you are reading from some pre-processed source, where a non-numeric input is not just a user mistake, but represents actual failure/curruption somewhere.

Alternatives include:

SysUtils:
function TryStrToInt(const S: string; out Value: Integer): Boolean;

And of course the base Pascal (predates Delphi and Object Pascal) conversion function, on which the other two functions are actually built:

procedure Val(S; var V; var Code: Integer);

Which takes a string and a numeric variable (integer, float, etc) and attempts to convert it. If Code=0 then conversion was successful to the type of the variable passed. Otherwise Code has the index in the string where the problem was encountered.

Share this post


Link to post
Share on other sites
Woa, you know what? I really dont like Delphi, but a, beginning to like it because of the kind of inbuild functions it has :-) If only the IDE was as easy to use as VB.NET ! :D

Thank you very much Michalson, I appreciate the help :-)

I really hope when the lecturer was telling me to "Try StrToInt" he wasnt meaning "TryStrToInt" :D

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this