Hoang Nguyen Hoang Nguyen - 1 month ago 21
Pascal Question

Pascal Boolean return value?

I'm currently working on an exercise of testing Boolean value from user input, as being presented below:

function ReadBoolean(prompt: String): Boolean;
var
choice: String;
exit: boolean;
begin
repeat
begin
WriteLn(prompt);
ReadLn(choice);
case choice of
'yes','y','t','true': exit := true;
'no','n','f','false': exit := false;
else
WriteLn('Not a boolean input. Enter again: ');
end;
end;
until exit=true or exit=false;
result := exit;
end;


It is expected to keep looping asking for value until it receives the input from specified string, however at my first attempt when I try to input 'fred' the boolean variable is automatically assigned as TRUE and exit the function.

Any helps would be very appreciated.

Answer

As my understanding, you only want the loop to end when user enters some specific strings.

It can be achieved by modifying the until condition like this:

choice='yes' or choice='y' or choice='t' or choice='true' or choice='no' or choice='n' or choice='f' or choice='false'

Or alternatively, create an indefinite loop and break it when user enters an expected string:

while true do
  ...
  'yes','y','t','true':
    begin
      exit := true;
      break;
    end;
  'no','n','f','false':
    begin
      exit := false;
      break;
    end;
  ...
end;