'StrtoIntDef Infinite While Loop

For some reason my program is stuck repeating this loop when I call the strtointdef function. It appears as though when I put in input for my loop, it first runs the loop with the input I provide, and then automatically starts the loop again with the failure input of strtointdef. How do I fix this?

while (choice < 5) AND (choice > 0) do
begin
  write('input: ');
  read(choice_string);
  choice := StrToIntDef(choice_string, 6);
  writeln(choice);

  if (choice = 6) then
  begin
    writeln('Invalid input!');
    write('input:');
    read(choice_string);
    choice := StrToIntDef(choice_string, 5);
  end; 
end;


Solution 1:[1]

Replace the two read(choice_string) with readln(choice_string). If you use read, the next read will not skip to the end of line and will not query a new input (normally the second input to string choice_string will be empty if you use read, you can verify this by writeln(choice_string)).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ken White