Search code examples
batch-filecmd

How do I make a batch file ask for user input?


I'm trying to make a batch file-based game, and i want to be able to collect user input. It should be a bit like the pause command, but asks for input from the user.

I don't have much code yet, because this is at the start of a program, but heres what I have so far:

@echo off
echo Start the game? [Y/N]

Here's what the output should look like:

Start the game? [Y/N]
y

Does anyone know what I can do to solve this?


Solution

  • For simple yes/no selection use choice then test errorlevel - for example:

    choice /N /M "Start the game? [Y/N] "
    if %errorlevel%==1 goto start else goto end
    
    :start
    :: Do something here
    
    :end
    :: Finish here
    

    Run choice /? for additional options. Note that choice displays the options and the ? automatically like:

    Start the game [Y,N]?
    

    To get the exact text you suggested, supress the options and put them in the prompt:

    choice /N /M "Start the game? [Y/N] "
    

    For more complex user input you can set an environment variable from a prompted user input using syntax:

    set /P <environment variable name>=<prompt>
    

    then you test the environment variable string however you require.

    For example, although overkill for single character y/n entries where choice is the simpler option:

    @echo off
    
    :: Get input
    :input_start_yn
    set /P ANSWER=Start the game? [Y/N] %=%
    if "%ANSWER%"=="Y" goto start
    if "%ANSWER%"=="y" goto start
    if "%ANSWER%"=="N" goto end
    if "%ANSWER%"=="n" goto end
    goto input_start_yn
    
    :start
    :: Do something here
    
    :end
    :: Finish here
    

    The environment variable solution has the advantage of storing user input permanently, whereas errorlevel is temporary and will be overwritten by subsequent commands. It also allows string entry rather then single characters, so can be used for more complex input.