Pascal: Converting strings to numeric variables (2 of 2)

Begin (*STRFP*)
Numeric:=['0'..'9'];
Exponent:=['E','e'];
Modifier:=['+','-','.',','];
DP:=False; EX:=False; IM:=True;
MN:=False; MX:=False; SN:=False;
DEC:=0; DEX:=0; EDP:=0; INX:=1;
LEN:=Length(STR); FP:=0;
STRFP:=False;
Search; (* Find start of number *)
While INX<=LEN Do Begin
CH:=STR[INX];
If CH in Numeric+Exponent+Modifier
Then Begin
If CH in Numeric
Then If EX
Then Begin
If DEX<1000 Then (* Exponent *)
DEX:=DEX*10+ORD(CH)-ORD('0');
SN:=True
End

Else Begin
If FP<1.0E8
Then (* Mantissa *)
FP:=FP*10+ORD(CH)-ORD('0')
Else EDP:=EDP+1;
If DP Then
(* Digits to right of DP *)
DEC:=DEC+1; IM:=False;
SN:=True
End
Else Case CH of
'+': If SN Then
(* Duplicate '+' sign *)
Terminate
Else SN:=True
'-': If SN Then
(* Duplicate '-' sign *)
Terminate
Else Begin
If EX Then MX:=True
Else MN:=True;
SN:=True
End;
'.': If DP of EX Then
(* Duplicate '.' *)
Terminate
Else DP:=True;
'E','e': If EX Then Terminate
(* Duplicate 'E' *)
Else Begin
If IM Then
(* Implied mantissa *)
FP:=1.0;
EX:=True;
SN:=False
End;
End; (*Case*)
INX:=INX+1
End
Else Terminate (* End of number *)
END;
Terminate (* End of string *)
End;

Function Strint; (* String to Integer *)

Var FP: real;

Begin
Strint:=STRFP (STR,FP); (* First convert to real *)
If ABS(FP)<=MasInt
Then INT:=ROUND(FP) (* then round to integer *)
Else Begin
String:=False; (* Integer out of range *)
INT:=0
End
End;

Begin (* Unit Initialization *)
End.

This sample program illustrates the use of STRINGSTUF. Use the compiler $V-
option to override the normal string length checking.

Program Stringtest;

Uses STRINGSTUF; (* tests STRINGSTUF library unit *)

Var Input,STR: string;
INT: integer;
FP: real;

Begin
Page (output);
Writeln ('STRINGSTUF String => Numeric Conversion:');
Repeat
Writeln;
Write ('String : ');
Readln (input);
(*$V-*)
If STRFP (input,FP) Then
Begin
Writelnn (' real: ',FP);
If Strint (input,INT)
Then Writeln ('integer: ',INT)
Else Writeln('integer: Out of range.')
End
Else Writeln('No numeric value in string.');
(*$V+*)
Until input=''
End.

Published Date: Feb 18, 2012