Date : Mon, 04 Jul 1988 16:32:26 GMT
From : ted@sbcs.sunysb.edu (Dr. Ted Carnevale)
Subject: Pascal, recursion, and buffered input
There seems to be some confusion about these topics and the capabilities of
at least one Pascal compiler for "itty bitty micros," as some wag put it.
The difficulties arose about a program like this, which ought to
accept keyboard input until a space is encountered,
and then echo the entire input string backwards.
===========
PROGRAM tryit(input,output);
PROCEDURE readwrite;
VAR nextchar:char;
BEGIN
read(nextchar); if nextchar <> ' ' then readwrite; write(nextchar);
END;
BEGIN
writeln('Type in a word that ends with a space');
readwrite
END.
===========
There are two reasons this program doesn't work properly with Turbo Pascal:
Turbo buffers keyboard input, and recursion is NOT enabled as a default.
It really isn't necessary to resort to arrays for temporary storage of
keyboard input. Simply enabling recursion with the {$A-} option and
turning off input buffering takes care of most of the problem:
===========
PROGRAM tryitr(input,output);
(* With Turbo Pascal this program works like so:
print message
REPEAT
accept keyboard input until CR is encountered
UNTIL input stream contains a blank
starting with the blank and working backward, print out the input stream
Thus this input stream:
onetwothree four five<CR>
produces this output:
eerhtowteno
and this input stream:
one<CR>
two<CR>
three four five<CR>
produces this output:
eerht
owt
eno
*)
(* enable recursion *)
{$A-}
(* use standard Pascal I/O rather than buffered keyboard input *)
{$B-}
PROCEDURE readwrite;
VAR nextchar:char;
BEGIN
read(nextchar); if nextchar <> ' ' then readwrite; write(nextchar);
END;
BEGIN
writeln('Type in a word that ends with a space');
readwrite
END.
===========
Still, the program doesn't quite work properly. It should produce its
output as soon as a blank occurs in the input stream, instead of waiting
for a carriage return to tell it to process an input line. Reading from
the "keyboard" input device instead of standard input takes care of this
last problem. Note that the {$B-} switch is no longer needed--"keyboard"
input is not buffered.
===========
PROGRAM trykbd(input,output);
(* With Turbo Pascal this program works like so:
print message
REPEAT
accept input stream
UNTIL blank is encountered
starting with the blank and working backward, print out the input stream
Thus this input stream:
onetwothreeB
produces this output:
Beerhtowteno
where B is a blank
*)
(* enable recursion *)
{$A-}
PROCEDURE readwrite;
VAR nextchar:char;
BEGIN
read(Kbd,nextchar); write(nextchar);
if nextchar <> ' ' then readwrite; write(nextchar);
END;
BEGIN
writeln('Type in a word that ends with a space');
readwrite
END.
===========