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.