NASutils Knowledge BaseUnofficialPolski

Pascal · lesson 11 of 30 · Decisions and loopsCheck what the user typed

TryStrToInt reads a whole number from a text and says whether that worked. The loop asks until the answer is in the set [1..8].

Programming on the NAS › Pascal in 30 lessons

11-check-input.pas Download 11-check-input.pas

program CheckInput;
{$mode objfpc}{$H+}
uses
  SysUtils;
var
  Line: string;
  Number: Integer;
begin
  repeat
    Write('A number from 1 to 8: ');
    if Eof then
    begin
      WriteLn('No more input');
      Halt(1);
    end;
    ReadLn(Line);
    if not TryStrToInt(Line, Number) then
    begin
      WriteLn('"', Line, '" is not a number');
      Continue;
    end;
    if Number in [1..8] then
      Break;
    WriteLn(Number, ' is out of range');
  until False;
  WriteLn('Disk ', Number, ' it is');
end.

Terminal

$ ./11-check-input
A number from 1 to 8: three
"three" is not a number
A number from 1 to 8: 12
12 is out of range
A number from 1 to 8: 3
Disk 3 it is

Exercise

Give up after three wrong answers.