Try and Catch In Pascal

前端 未结 3 1638
甜味超标
甜味超标 2021-01-19 18:11

I\'m using Dev-Pas 1.9.2 and am trying to make sure the program doesn\'t crash when a symbol or a letter value is entered.

I\'ve googled and googled and can\'t find

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-19 18:20

    Change your code to accept a Char instead; if you need an integer for some reason, handle the conversion afterward.

    This works in Delphi; unless you can't use sets like ['1'..'4','9'] and set operators, it should work fine.

    Function GetMenuChoice : Char;
    Var
      OptionChosen : Char;
    Begin
      repeat
        Write('Please enter your choice: ');
        Readln(OptionChosen);
    
        If not (OptionChosen in ['1'..'4', '9'])
          Then
            Begin
              Writeln;
              Writeln('That was not one of the allowed options.  Please try again: ');
            End;
      until OptionChosen in ['1'..'4', '9'];
      GetMenuChoice := OptionChosen;
    End;
    

    If you absolutely need a number to be returned, change the return type back to integer (or byte) and then change the final line to:

    GetMenuChoice := Ord(OptionChosen) - 48;  
    

    or

    GetMenuChoice := Ord(OptionChosen) - Ord('0');
    

提交回复
热议问题