55: How can I test and
convert a numerical string into a real?
A1: An easy task in
Turbo Pascal but in standard Pascal this
frequent task is much trickier. Here are both the Turbo Pascal and
Standard Pascal versions for general edification :-).
(* Convert and test a numerical string with Turbo Pascal *)
function DIGVALFN (mj : string; var ok : boolean) : real;
var k : integer;
x : real;
begin
Val (mj, x, k);
ok := k = 0;
if ok then digvalfn := x else digvalfn := 0;
end; (* digvalfn *)
{}
(* Convert and test a numerical string with standard Pascal
routines only *)
procedure DIGVAL (mj : string; var number : real; var ok :
boolean);
label 1;
var il, lenl, pl, kl1, kl2 : integer;
nrol : boolean;
numberdl : real;
begin
ok := true; lenl := Length (mj); nrol := false; pl := 0; number := 0.0;
if lenl = 0 then ok := false;
for il:=2 to lenl do if (mj[il]='-') or (mj[il]='+') then ok := false;
for il:=1 to lenl do
case mj[il] of
'0'..'9','+','-','.' : ; else ok := false;
end;
for il:=1 to lenl do
case mj[il] of '0'..'9' : begin nrol := true; goto 1; end; end;
1: if nrol = false then ok := false;
for il:=1 to lenl do if mj[il] = '.' then pl := pl + 1;
if pl > 1 then ok := false;
kl1:=1; kl2:=lenl+1; if (mj[1]='-') or (mj[1]='+') then kl1 := 2;
for il:=1 to lenl do if mj[il] = '.' then kl2 := il;
if kl2-kl1 > 38 then ok := false;
if ok then
begin
number:=0; numberdl:=0;
for il:=kl1 to kl2-1 do number := (ord(mj[il])-48)+10*number;
if kl2 < lenl+1 then
for il:=lenl downto kl2+1 do
numberdl := (ord(mj[il])-48)/10+numberdl/10;
number := number + numberdl;
if mj[1]='-' then number := -number;
end; {if ok}
end; (* digval *)
{}
procedure TEST;
var s : string; r : real; ok : boolean;
begin
s := '123.41';
r := DIGVALFN (s, ok);
if ok then writeln (r) else writeln ('Error in ', s);
DIGVAL (s, r, ok);
if ok then writeln (r) else writeln ('Error in ', s);
end;
A2: The conversion can
be in the other directorion as well. Here is
how to convert an integer into a string with standard Pascal
routines only.
function CHRIVLFN (number : integer) : string;
var il, pl, al : integer;
cl, mj : string;
isNeg : boolean;
begin
if number < 0 then begin
isNeg := true; number := -number; end
else isNeg := false;
pl := 0; mj := ''; cl := '';
repeat
pl := pl + 1;
al := number mod 10;
cl := cl + chr(al+48);
number := number div 10;
until number = 0;
if isNeg then begin pl := pl + 1; cl[pl] := '-'; end;
for il := 1 to pl do mj := mj + cl[pl+1-il];
chrivlfn := mj;
end; (* chrivlfn *)
{}
procedure TEST;
var s : string; j : integer;
begin
j := 12341;
s := CHRIVLFN (j);
writeln (s);
end;