I was doing some coding today and came across a problem someone else faced and I couldnt answer it for them. I'll explain the concept in the little program below....

Program between;
uses crt;
   value: integer;

     writeln('Please enter value');

...Basically what the programmer wanted to do was do an error message if a word or even a char was entered instead of a number so the program doesnt crash like how its setup now.

I started to think well an easy way would be if there was a variable type that stored both integer, char and string. But I dont think there is one?

So the only idea I had was to do an IF Else statement where ELSE displays the error message and asks the user to enter a number this time. However since the value here is stored as an integer I wasnt sure how to get around this.

Any ideas/help would be greatly appreciated.

Seems theres a Val feature that basically converts strings into integers, Str does the opposite. Val in this example also has the third parameter as the error display.

program TriangleWait (input, output);
      b, h: integer; {Base & Height}
      A: real; {Area}
      h_string : string; {Input string for Height}
      Err : integer; {Error flag set by Val()}
      {------------Introduction & Setup------------------}
      writeln('This program calculates and prints the area of a triangle');
      writeln('after you enter their dimensions.');
      writeln('When asked to, type in a dimension and hit the ENTER key.');
      {-------------------Inputting Data------------------}
         write('What is the triangle''s base? ');
         if b <= 0 then
            writeln('The base needs to be GREATER than zero.')
      Until b > 0;
      {------VERY User-Friendly------}
         write('What is the triangle''s height? ');
         val(h_string, h, Err);
         if Err > 0 then
            writeln('An illegal character was found at character #', Err, '.')
         else if h <= 0 then
            writeln('The height needs to be GREATER than zero.')
      Until (h > 0) AND (Err = 0);
      A := b * h / 2;
      {-------------------Printing Results------------------}
      writeln('The area of a triangle with a base of ', b:0, ' units and');
      writeln('a height of ', h:0, ' units is ', A:0:1, ' square units.'); 

i haven't worked with pascal since 2002, now i'm a delphi happy programmer:). in delphi exist what you want, data type is called "variant".

hehe well unfortunately I dont have a choice at the moment, this year my course is using Pascal :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.