Search code examples
variablesbatch-fileif-statementsetprompt

IF Statement in batch not working?


I'm coding a game in batch right now, and I've not gone very far when I encountered this problem. I'm trying to set a variable for a user answer, then use that answer for an IF statement, but for some reason it always goes to the :Quit block. Any ideas on how to fix this?

Echo . Are you ready?
Echo Your options are:
call :colorEcho C "================="
Echo.
Echo 1. Yes
Echo 2. No
call :colorEcho C "================="
Echo.
Echo Please enter the number corresponding to your answer.
set /p Answer1 = "Enter your choice: "
if "%Answer1%" == "1" goto Game
if "%Answer1%" == "2" goto Quit

:Quit
Echo You have chosen to quit.
pause
exit

:Game
::Game goes here.
Echo Test
pause

pause
exit

:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i

colorEcho just sets a different color for a string of text.

This is what happens when I run the game:

Option 1 chosen:

Option 1 chosen

Option 2 chosen:

Option 2 chosen

Thanks in advance!

Spades


Solution

  • That's because %Answer1% is not defined.

    set /p Answer1 = "Enter your choice: "
    

    sets a variable named %Answer1 % (note the space!)

    Remove the spaces around the =.