批处理脚本:在IF语句中使用GOTO

时间:2017-06-23 13:40:26

标签: batch-file

当你到达用户输入部分时,无论我输入什么(桌子,火,门),它总是进入壁炉。我的if语法有问题吗?

    @echo off
    color C
    title RG Text Game
    echo -------------------------------------------------
    echo Welcome to the Game!
    echo.
    echo -------------------------------------------------
    echo.
    pause

    echo.
    echo Blah bah blah story story
    echo What do you want to do?
    echo Choices: fire/desk/door
    set /p choice= 
    if %choice%=="fire" GOTO fireplace
    if %choice%=="desk" GOTO desk
    if %choice%=="door" GOTO door

    :fireplace
    echo.
    echo You come to the fireplace.
    echo.
    pause

    :desk
    echo.
    echo You go to the desk.
    echo.

    :door
    echo.
    echo You go to the door.
    echo.

3 个答案:

答案 0 :(得分:2)

Doublequote %choice%或它不相等:desk不等于"desk"

使用Labelgoto:eof退出exit/b阻止。

/i开关与IF一起使用,这样您也可以使用DESKDesK

 if /i "%choice%"=="fire" GOTO fireplace
 if /i "%choice%"=="desk" GOTO desk
 if /i "%choice%"=="door" GOTO door
 goto:error

:fireplace
echo.
echo You come to the fireplace.
echo.
pause
exit/b

:desk
echo.
echo You go to the desk.
echo.
exit/b

:door
echo.
echo You go to the door.
echo.
exit/b

答案 1 :(得分:0)

你需要保护每个目标区块的入口点,否则当它完成执行目标区块时,它将会落入"下一个街区。

在任何标签行(例如:fireplace)之前,您需要GOTO来确保程序流程不会落入"下一个例程:

@echo off
color C
title RG Text Game
echo -------------------------------------------------
echo Welcome to the Game!
echo.
echo -------------------------------------------------
echo.
pause

echo.
echo Blah bah blah story story
echo What do you want to do?
echo Choices: fire/desk/door
set /p choice= 
if /I "%choice%" EQU "fire" GOTO fireplace
if /I "%choice%" EQU "desk" GOTO desk
if /I "%choice%" EQU "door" GOTO door
GOTO END

:fireplace
echo.
echo You come to the fireplace.
echo.
pause
GOTO END

:desk
echo.
echo You go to the desk.
echo.
GOTO END

:door
echo.
echo You go to the door.
echo.

:END

还请注意IF语句的更改。这些允许您处理键入FIREFire而非fire的情况。

答案 2 :(得分:0)

除了Jeff和SachaDee的提示,
如果您将所有标签命名为等于您可以使用循环的选项

For %%A in (fire desk door) Do If /i "%choice%" equ "%%A" Goto %choice%

或者使用数量有限的选项,您可以使用choice.exe并使用单个字母答案(不需要输入)并评估返回的错误级别。