"if" 批处理语句:当输入本应为数字但包含带空格的单词时文件崩溃

"if" statements in batch: file crashes when the input is supposed to be a number, but instead has words with spaces

所以,我在批处理文件中有一个 set /p 东西。要让用户继续,他们必须键入“2”。我似乎无法在任何地方找到我的具体问题。

@echo off
echo "What is 1+1"

set /p oneplusone=Type Answer Here: 

if %oneplusone%==2 goto correct
if %oneplusone% neq 2 goto incorrect

:correct
cls
echo Correct!
pause
goto youranswer

:incorrect
cls
echo Wrong.
pause
goto youranswer

:youranswer
cls
echo You answered: %oneplusone%

现在,如果用户键入没有 space 的 number/word,一切正常,它会显示您想要的答案。

但是,假设您键入 "hi there" 和 space 之类的内容,批处理文件会立即关闭。只有当答案需要是一个数字时才会发生这种情况,并且您键入的内容涉及 space.

有什么帮助吗?

提前致谢。

您可以使用以下方法检查您的答案是否为数字:

set /a test=%oneplusone%*1
if %test%==0 goto notValid

还有另一个标签,让你的代码变成这样

@echo off
echo "What is 1+1"

set /p oneplusone=Type Answer Here: 
set /a test=%oneplusone%*1
if %test%==0 goto notValid
if %oneplusone%==2 goto correct
if %oneplusone% neq 2 goto incorrect

:correct
cls
echo Correct!
pause
goto youranswer

:incorrect
cls
echo Wrong.
pause
goto youranswer

:notValid
cls
echo Your input is not valid

pause
goto youranswer

:youranswer
cls
echo You answered: %oneplusone%