Batch File input validation - Make sure user entered an integer

前端 未结 16 2414
抹茶落季
抹茶落季 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:15

    As pointed out by ghostdog74, the answers posted by Joey Mar 26 '09 (score 10) and Wouter van Nifterick Mar 26 '09 (score 5) don't work.

    The answer posted by Joey Mar 25 '10 (score 2) does work, except that redirection symbols and '&' cause syntax errors.

    I think the best and simplest solution is the one posted by Sager Oct 8 '14 (score 0). Unfortunately, it has a typo: ‘"%a"’ should be ‘"%a%"’.

    Here's a batch file based on Sager's answer. Redirection symbols and '&' in the input don't cause problems. The only problems I could find were caused by strings containing double quotes.

    @echo off & setlocal enableextensions & echo.
    set /p input=Enter a string:
    SET "x=" & for /f "delims=0123456789" %%i in ("%input%") do set x=%%i
    if defined x (echo Non-numeral: "%x:~0,1%") else (echo No non-numerals)
    

提交回复
热议问题