Batch File input validation - Make sure user entered an integer

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

    If you want some sort of a loop and default set up for that particular question, then here's my method for doing this.

    Notes on the code within.

    @echo off
    setlocal EnableDelayedExpansion
    set "ans1_Def=2"
    
    :Q1
    set /p "ans1=Opt 1 of 1 [Value 1-5 / Default !ans1_Def!]: "
    
    :: If not defined section. This will use the default once the ENTER key has been
    :: pressed and then go to :Q2.
    if not defined ans1 (
      echo/ & echo ENTER hit and the default used. Default is still: !ans1_Def! & echo/
      set "ans1=!ans1_Def!" && goto :Q2 )
    
    :: This section will check the validity of the answer. The "^[1-5]$" will work
    :: for only numbers between one and five in this example but this can be changed
    :: to pretty much suit the majority of cases. This section will also undefine
    :: the ans1 variable again so that hitting the ENTER key at the question
    :: will work.
    echo %ans1%|findstr /r /c:"^[1-5]$" >nul
    if errorlevel 1 (
      echo/ & echo At errorlevel 1. Wrong format used. Default is still: !ans1_Def! & echo/
      set "ans1=" && goto Q1
      ) else ( echo Correct format has been used. %ans1% is the one. && goto :Q2 )
    
    :Q2
    echo/
    echo -----------------------------
    echo/
    echo Now at the next question
    echo !ans1!
    echo/
    pause
    exit
    

提交回复
热议问题