Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 379
  • Last Modified:

Pascal data type checking

In pascal, when I defined a integer data type and use a readling statement to get data from user input,
there is a run-time error if the user input characters but not numeric
so how do I manual checking the user input is the correct data type I defined
  • 3
  • 2
1 Solution
a quick fix is to readln into a string, and then convert the string to an integer using the val procedure

the val procedure will do error checking for you

program foo;
  s :string;
  n :integer;
  code :integer;
  write ('Enter an integer: ');
  val(s, n, code);
  if code <> 0 then
    writeln('Not an integer.  Error at position: ', code);
    writeln('the integer you entered is ',n);


The val procedure takes three parameters.  The first is a string that you wish to convert to an integer.  The second is the integer variable you want to store it in.  The third is the variable you want to store the "error" code in.  If the code is 0, the conversion took place successfully.  If it is not zero, the code variable will hold the index of the position in the string where the error occurred (such as an alphabetic character inside the string, etc.).

The reason for doing it this way is so you can perform you own error handling...a run-time error is unlikely to result regardless of what you enter into a string variable.
adrianmakAuthor Commented:

It works but it seems only work for integer but not include real numbers
val should work with both integers and reals

are you sure you set the type of your number variable to "real"?
(the "code" variable must always be an integer though)
adrianmakAuthor Commented:
it works now.

It is depend on the data type of the variable n
if it define am integer then if i input a real number e.g. 5.6
it return of val is false
if defined as real it is true

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now