如何设置输入以成批接收前一个,前两个或前三个字符?

时间:2019-09-16 10:39:03

标签: batch-file choice

我正在尝试弄清所提供代码的{​​{1}}部分是如何工作的。

我认为"%var:~,1%"会接受第一个正确的字符,而之后忽略其他所有内容。 "%var:~,1%"将只接受前两个正确的字符,依此类推。在此示例中,“ Y”足以满足“ YES”。 “ NO”足以满足“ NOO”,“ CLS”足以满足“ CLS”

发生的只有选项3,“ CLS”是有效选项。我可以将YES和NOO更改为"%var:~,2%",以便它们是有效的选项。但是"%var:~,3%"将如何接受一个字符的输入?

if /I "%var:~,1%" EQU "YES" goto :yes

1 个答案:

答案 0 :(得分:1)

@TripeHound在评论中已经说明,您正在针对一个单词测试单个字符。应该只是if /i "%var:~0,1%"=="y"

但是更好的方法是使用choice

@echo off
:start
choice /C YNC /M "Press Y for Yes, N for No or C for Cancel.
goto :%errorlevel%

:3
echo this will CLS but you have to type the first three letters correct
pause
cls
goto :start

:2
echo this is NO but you have to type the first two letters correct
goto :start

:1
echo this is YES but you only have to type first letter correct
goto :start

如果确定不使用choice,则仅使用用户输入的单词的第一个字符,这与使用set /p相似。

@echo off
:start
set /p var=is this a yes or no question?
if /i not "%var:~0,1%"=="y" if /i not "%var:~0,1%"=="n" if not "%var:~0,1%"=="c" echo Incorrect choice & goto :start
goto :%var:~0,1%

:c
:C
echo this will CLS but you have to type the first three letters correct
pause
cls
goto :start

:n
:N
echo this is NO but you have to type the first two letters correct
goto :start

:y
:Y
echo this is YES but you only have to type first letter correct
goto :start