I'm embarrassed to admit that I cannot understand why in this very simple example that the "readln(age);" statement in the "else if" clause ignores the first integer entered in response to the "writeln('How old are you ',name:length(name),'?');" statement aroune line 16.

It seems clear that the culprit is the "ch := readkey;" statement on line 18.
To enter a valid age, some key must first be pressed (other than <Enter> (ASCII 13) which is trapped by the "if ch = #13 then" statement.

It does not seem to matter if the "age" variable is typed as a string or integer.

What happens is that if one enters two characters or integers, only the second is stored in the "age" variable. For example, to input an age of "25", I must first press some other key on the keyboard first, then enter "25" for "25" to be stored in the "age" variable.

Any help understanding this would be sincerely appreciated. Perhaps the entire approach is incorrect?

PROGRAM t5;
uses crt;

var
  name,age  : string;
  ch        : char;

procedure greet;
  begin

    clrscr;
    writeln('What''s your name? ');
    readln(name);
    clrscr;
    writeln('Hi, ',name:length(name));
    writeln('How old are you ',name:length(name),'?');

    ch := readkey;
      if ch = #13 then
        begin
          writeln('Please enter a valid age!');
          writeln ('You pressed the ','"','Enter','"',' key ','("',ord(ch),'")');
          readln;
          writeln('Bye!');
          readln;
        end

      else if ch <> #13 then

        begin
          readln(age);
          writeln('Gee, ',age,', - that''s really old!');
          readln;
        end;
  end;


BEGIN

  greet;

END.

Frankly, I'd replace the line with readkey with a simple readln(age). Now to detect they want to exit we check the string length.

-> Side note. Next time post with a code paste so line numbers show up.

The replace for the line with the if ch = #13 would be something like:

if Length(age) = 0 then
Source: https://www.freepascal.org/docs-html/rtl/system/length.html

I'm sure you can correct the else if from here on out but there was no need to have more than "else".

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.