Type Checking In Pascal

戏子无情 提交于 2021-01-27 04:32:41

问题


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.

回答1:


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.




回答2:


Maybe Val procedure can help you. Here is one for fpc. But change your logic to read into a String and validate it using Val. You can find a sample here.




回答3:


That 's too easy, see my code below:

program int_check;
uses crt;
var n:real;
begin 
     clrscr;
     write('Enter a number: ');readln(n);
     if n-round(n)=0 then write('Integer!') else write('Not an Integer!');
     readln;
end.

You see, no string, no IOcheck, and fits your form!




回答4:


Since number is an Integer, the app will fail if the user types a non-numeric value. You'll never reach the if statement.




回答5:


Use frac(n) directly

program int_check; uses crt; var n:real; begin clrscr; write('Enter a number: ');readln(n); if frac(n)=0 then write('Integer!') else write('Not an Integer!'); readln; end.



来源:https://stackoverflow.com/questions/10052076/type-checking-in-pascal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!