Batch File input validation - Make sure user entered an integer

前端 未结 16 2347
抹茶落季
抹茶落季 2020-12-03 14:33

I\'m experimenting with a Windows batch file to perform a simple operation which requires the user to enter a non-negative integer. I\'m using simple batch-file techniques t

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 15:09

    Thanks all. I was trying to make it harder for myself looking at loops and string manipulation. I used your tips on math evaluation and comparison. Here's what I finally came up with as my concept script:

    :Top
    @ECHO OFF
    ECHO.
    ECHO ---------------------------------------
    SET /P UserInput=Please Enter a Number: 
    ECHO.
    ECHO UserInput = %UserInput%
    ECHO.
    SET /A Evaluated=UserInput
    ECHO Math-Evaluated UserInput = %Evaluated%
    if %Evaluated% EQU %UserInput% (
        ECHO Integer
        IF %UserInput% GTR 0 ( ECHO Positive )
        IF %UserInput% LSS 0 ( ECHO Negative )
        IF %UserInput% EQU 0 ( ECHO Zero )
        REM - Other Comparison operators for numbers
        REM - LEQ - Less Than or Equal To
        REM - GEQ - Greater Than or Equal To
        REM - NEQ - Not Equal To
    ) ELSE (
        REM - Non-numbers and decimal numbers get kicked out here
        ECHO Non-Integer
    )
    
    GOTO Top
    

    This method catches all numbers and can detect whether it's positive, negative, or zero. Any decimal or string will be detected as non-integers. The only edge case I've found is a string with spaces. For example, the text "Number 1" will cause the script to crash/close when the user input is evaluated as math. But in my situation, this is fine. I don't want my script to go on with invalid input.

提交回复
热议问题