Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Checking In Pascal

Tags:

pascal

fpc

I'm just wondering how it's possible to do type checking in pascal? I have been searching for hours now but I haven't been able to find anything useful.

Example:

var 
number: Integer;

begin
  write('Enter a number: ');
  read(number);

  if {How am I supposed to check if 'number' is an Integer here?}
  then writeln(number)
  else writeln('Invalid input')
end.
like image 560
Radix Avatar asked Apr 07 '12 05:04

Radix


1 Answers

You are actually hitting the I/O type checking. You can work around this by disabling it temporarily and then checking the result:

 {$I-}  //turn off IO checking temporarily
 read(i);
 {$I+}  // and back on

 if ioresult=0 then  // check the result of the last IO operation
   writeln('integer successfully read:',number)
 else
   writeln('invalid input');

Note: the typical answer is often "just read a string and do the conversion yourself", however it is difficult to do that nicely without making assumptions about the terminal type.

For clear and simple programs where you just want somewhat validated input, the above trick (and a loop around it that repeats on error) is enough.

like image 92
Marco van de Voort Avatar answered Sep 19 '22 18:09

Marco van de Voort