我只是想知道如何在pascal中进行类型检查?我已经搜寻了几个小时,但找不到任何有用的东西。
例:
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.
Run Code Online (Sandbox Code Playgroud)
您实际上是在执行 I/O 类型检查。您可以通过暂时禁用它然后检查结果来解决此问题:
{$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');
Run Code Online (Sandbox Code Playgroud)
注意:典型的答案通常是“只读取一个字符串并自己进行转换”,但是如果不对终端类型做出假设,很难很好地做到这一点。
对于您只想要一些经过验证的输入的清晰和简单的程序,上述技巧(以及在错误时重复的循环)就足够了。