Try and Catch In Pascal

前端 未结 3 1603
甜味超标
甜味超标 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:16

    (in addition to Ken White's)

    1. I think one can use READ for a char typed variable, and save the user to type enter.

    2. But I would go for a string typed version and use VAL.

      • It is something more encoding agnostic, and
      • the principle extends beyond value 9.
      • requires an enter though, and heavy input will mess up your screen.

    For the latter there are other methods (e.g. using unit Crt or Video), but that probably goes beyond the scope of the assignment

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2021-01-19 18:23

    Do you really want to accept exactly four different possible inputs? (The numbers 1, 2, 3, 4, and 9) That's what you're asking for at the moment.

    Note: even with a change like the first answerer suggested, your code has a major problem. What happens if a 5 or Q is given ... you complain, AND THEN EXIT THE ROUTINE.

    In the original code, if I enter a 100, you'll print the "That was not allowed"... and then return 100 to the caller.

    Hint: loop.

    Hint 2: ensure you don't loop forever

    BTW, NEVER do: ord (some character) - 48 instead, always use: ord (some character) - ord ('0')

    Why? Two obvious reasons:

    1. readability. What's 48?

    2. correctness. If you're compiled on a non-ASCII system, 48 may not be the character code for 0.

    Stan

    0 讨论(0)
提交回复
热议问题