unit SafeInput;
{$mode objfpc}{$H+}
{$codepage UTF-8}
interface
uses
{$ifdef unix}cwstring,{$endif}
SysUtils,
ConsoleUtils;
function ReadInteger(const APrompt: string): Integer;
function ReadFloat(const APrompt: string): Double;
function ReadIntegerInRange(const APrompt: string; AMin, AMax: Integer): Integer;
implementation
function ReadInteger(const APrompt: string): Integer;
var
S: string;
begin
repeat
Write(APrompt);
ReadLn(S);
try
Result := StrToInt(S);
Exit;
except
on E: EConvertError do
WriteLn('Ошибка: "', S, '" — не является числом. Попробуйте ещё раз.');
end;
until False;
end;
function ReadFloat(const APrompt: string): Double;
var
S: string;
begin
DefaultFormatSettings.DecimalSeparator := '.';
repeat
Write(APrompt);
ReadLn(S);
try
Result := StrToFloat(S);
Exit;
except
on E: EConvertError do
WriteLn('Ошибка: "', S, '" — не является числом. Попробуйте ещё раз.');
end;
until False;
end;
function ReadIntegerInRange(const APrompt: string; AMin, AMax: Integer): Integer;
begin
repeat
Result := ReadInteger(APrompt);
if (Result >= AMin) and (Result <= AMax) then
Exit
else
WriteLn('Ошибка: число должно быть от ', AMin, ' до ', AMax, '. Попробуйте ещё раз.');
until False;
end;
end.