Type Check

Data is only valid if it is of the correct data type, e.g. integer or real.

When an integer must be input with a statement such as readln(myInt), the entry of erroneous data of the wrong type e.g. q23 or 3.12 will generate a run-time error. This will not prevent the program from compiling, and no error message will be provided by the IDE. To prevent such run-time errors, input the integer as a string and validate the string before converting it to an integer. The built-in val procedure generates an integer from a string if the string is a valid representation of an integer.

The val procedure applied to an integer takes three parameters:

  1. A string parameter, passed by value, containing the string to be converted.
  2. A variable integer parameter to take the value of the string if the conversion is successful.
  3. Another variable integer parameter to be given the position of the first offending character if the string is not a valid representation of an integer.

In the example program, note that intRainfall and intErrorCode will be assigned values by the val procedure.

program ValidateInteger;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  intRainfall, intErrorCode : integer;
  strRainfall : string;
begin
   repeat
     write('Please enter the rainfall to the nearest mm. ');
     readln(strRainfall);
     val(strRainfall, intRainfall, intErrorCode);
     if intErrorCode > 0 then writeln('Error at character position ', intErrorcode);
   until intErrorCode = 0;
   writeln(intRainfall, ' mm accepted.');
   readln;
end.

To validate a real number, use the val procedure and declare the second parameter as a real number e.g. var realRainfall : real.

Programming - a skill for life!

Checking data to see if it is sensible