代码之家  ›  专栏  ›  技术社区  ›  ProCoder2040

如何使批处理文件要求用户输入?复制

  •  -2
  • ProCoder2040  · 技术社区  · 2 年前

    我正在尝试制作一个基于批处理文件的游戏,我希望能够收集用户输入。它应该有点像暂停命令,但要求用户输入。

    我还没有太多的代码,因为这是一个程序的开始,但这是我到目前为止所拥有的:

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

    输出应该是这样的:

    Start the game? [Y/N]
    y
    

    有人知道我能做些什么来解决这个问题吗?

    1 回复  |  直到 2 年前
        1
  •  -1
  •   Clifford    2 年前

    用于简单的是/否选择 choice 然后测试 errorlevel 例如

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

    choice /? 以获取更多选项。请注意 选择 显示选项和 ? 自动喜欢:

    Start the game [Y,N]?
    

    要获得您建议的确切文本,请取消选项并将其放入提示中:

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

    对于更复杂的用户输入,您可以使用有些晦涩的语法从提示的用户输入中设置环境变量:

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

    然后根据需要测试环境变量字符串。

    例如,虽然对于单个字符的y/n条目来说过于夸张,但 选择 是更简单的选项:

    @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
    

    环境变量解决方案的优点是永久存储用户输入,而 错误等级 是临时的,将被后续命令覆盖。它还允许字符串输入,而不是单个字符,因此可用于更复杂的输入。