Pascal中的类型检查 [英] Type Checking In Pascal

查看:79
本文介绍了Pascal中的类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何在pascal中进行类型检查?我已经搜索了几个小时,但找不到任何有用的信息.

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.

示例:

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.

推荐答案

您实际上是在进行I/O类型检查.您可以通过暂时禁用它,然后检查结果来解决此问题:

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.

这篇关于Pascal中的类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆