Goto was unexpected at this time - batch

2019-06-28 07:23发布

问题:

I am trying to make a batch text-based game. But i encountered a problem just starting to write it what I have never encountered before.

:menu
:: the game menu - opens when the game starts
cls
echo This game is still being made -- expermintal
echo Start Screen:
echo [1] View Changes
echo [2] Start Game
echo enter your choice:
set /p startchoice =
if %startchoice%==1 goto changes
if %startchoice%==2 goto startgame

When i type in either 1 or 2, it shows the error "goto was unexpected at this time" How do I fix it?

回答1:

Your startchoice isn't being set correctly. Use the alternate syntax for set /p where you supply the prompt there (and remove the space between startchoice and the assignment (=) operator - I think it's actually the cause of the problem, but you can reduce your batch file by a line if you use the set /p <variable>=<Prompt> syntax).

I added two targets for the goto, and echo statements so you could see they were reached:

:menu
:: the game menu - opens when the game starts
cls
echo This game is still being made -- expermintal
echo Start Screen:
echo [1] View Changes
echo [2] Start Game
set /p startchoice=Enter your choice:

if %startchoice%==1 goto changes
if %startchoice%==2 goto startgame
:changes
echo Changes
goto end
:startgame
echo StartGame
:end


回答2:

You need quotes around the if comparison and it didn't like you using set / p without a prompt. The following works:

:menu
:: the game menu - opens when the game starts
cls
echo This game is still being made -- expermintal
echo Start Screen:
echo [1] View Changes
echo [2] Start Game
set /p startchoice = "enter your choice: "
if "%startchoice%"=="1" goto changes
if "%startchoice%"=="2" goto startgame


回答3:

Instead of using environment variables, try this:

CHOICE
IF %ERRORLEVEL% EQU 1 goto changes
IF %ERRORLEVEL% EQU 2 goto startgame

Choice is a program that allows you to enter a number or y/n and returns an error code. %ERRORLEVEL% is a variable that holds the program's last error code.

You can do other comparisons, too.

EQU  - equal 
NEQ - not equal 
LSS - less than 
LEQ - less than or equal 
GTR - greater than 
GEQ - greater than or equal 


回答4:

Another Reason it could be malfuntioning is that you have not included the SET /P M= Variable Correctly... There should not be a space between the m and the equals sign.



标签: goto