[fpc-pascal] Something like "Is a number"?
A.J. Venter
ajventer at direq.org
Sat Jul 9 11:59:51 CEST 2005
> >You can use val(str, int/real, err)
> >
> >if err is 0, the string was converted to an integer or real (depending on
> >the type of int/real.
> >
> >John
>
> Thank you, it's working!!!
>
Yes that's the old Pascal version of StrToInt :) and it had errorchecking :)
Just for the record, like everything it has more than one answer, you could
also have done:
try
Int := strToInt(Str);
except
Int := -1 {Or whatever error number}
end;
Or if you wanted to prepend exceptions rather than catch them, the following
function could also work have worked (note you have to do a shortString cast,
AnsiStrings don't like access by character)
Function IsANumber (InStr : String) : Boolean
Var TempBool : Boolean;
Str : ShortString;
I : Integer;
Begin
Str := ShortString(InStr);
TempBool := True;
I := 1;
While (I <= Length(Str)) and (TempBool = True) do
Begin
TempBool := Str[I] in ['0'..'9'];
Inc(I);
end;
IsANumber := TempBool
end;
Of course, that's a rather ugly way to do it, I don't suggest it in practice
except for very special cases but I put it here to give an idea of the ways
you can interact between types. One of Pascal's (and by inheritance object
pascal's) greatest features is that it is not only strongly typed but has
very strict type checking, which prevents a very large number of the problems
C coders face. For starters you don't have to take measures against about a
potential buffer overflow every time you use strings, it does mean though
that getting data from one type to another is sometimes a little harder than
a simple cast (like in say java), but if you understand the ways in which
data types are actually implemented and how they relate to each other you can
do not only everything you can do in untyped or weakly-typed languages but a
great deal more.
Ciao
A.J.
More information about the fpc-pascal
mailing list