Function VAL (X) In UCSD PASCAL For Apple II
Michael Erperstorfer Vienna, Austria
Function VAL (X) is similar to BASIC'S VAL-function:
X must be a string of an integer number;
VAL returns a true integer number;
If X is no integer number VAL returns 0;
String X may have leading or trailing spaces.
PROGRAM VALTEST; VAR INPUT : STRING; FUNCTION VAL (S : STRING) : INTEGER; VAR START, I, LEN, O, V : INTEGER; NEG : BOOLEAN; BEGIN V : = 0; NEG: = FALSE; WHILE COPY (S, l, l) = ’ ’ DO S : = COPY (S, 2, LENGTH (S)-l); (* remove blanks from left *) WHILE COPY (S, LENGTH(S),1) = ’ ’ DO S : = COPY (S, l, LENGTH (S)-l); (* remove blanks from right *) START : = 1; IF COPY (S, 1,1) = ’-’ THEN BEGIN START: = 2; NEG: = TRUE END; (* if first char = ’-’ *) (* number is negative *) (* increment start value *) (* to skip ’-’ sign *) (* set neg-flag *) LEN: = LENGTH (S); FOR I: = START TO LEN DO BEGIN O: = ORD(S[I]); IF (O > 47) AND (O < 58) THEN (*check if char is number *) V : = V + TRUNC (PWROFTEN (LEN-I)) * (O-48) (* calculate value *) ELSE BEGIN (* if char is not number *) VAL: = 0; (* set value to 0 *) EXIT (VAL) (* and exit function *) END END; IF NEG THEN VAL: = -V ELSE VAL: = V END; BEGIN REPEAT WRITE (’ STRING : ’); READLN (INPUT); WRITELN (’ = ’, VAL (INPUT)) UNTIL INPUT = ’ ’ END.