您好我正在处理Windows批处理文件,如果用户没有输入字符串,我试图让程序结束,但是当我运行它并且不输入任何东西时,整个事情仍然运行。任何建议都会非常感谢。
:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name:
::If the user does not input anything go to end option
if "%studentName%"=="" goto end
:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%
:: Pauses screen while user reads secret number
pause
:: Clear screen for user.
cls
echo Hope you remeber that number, %studentName%!
:end
echo Usage: %0 studentName
pause
exit /b
答案 0 :(得分:2)
在常规批处理脚本中设置变量时,它们会一直存在于环境中,直到删除它们或关闭环境为止。您的问题源于这样一个事实,即您在没有首先准备环境的情况下给了%studentName%
一个值。您有两种选择:
@echo off
:: Clears the value of %studentName%. The quotes are to prevent extra spaces from sneaking onto the end
set "studentName="
:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name:
::If the user does not input anything go to end option
if "%studentName%"=="" goto end
:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%
:: Pauses screen while user reads secret number
pause
:: Clear screen for user.
cls
echo Hope you remeber that number, %studentName%!
:end
echo Usage: %0 studentName
pause
exit /b
优点:
缺点:
@echo off
setlocal
:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name:
::If the user does not input anything go to end option
if "%studentName%"=="" goto end
:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%
:: Pauses screen while user reads secret number
pause
:: Clear screen for user.
cls
echo Hope you remeber that number, %studentName%!
:end
echo Usage: %0 studentName
pause
exit /b
优点:
缺点:
答案 1 :(得分:1)
set /p studentName=Enter student name: || goto :end
启用命令扩展(默认配置,或者可以使用setlocal enableextensions
启用)条件运算符||
(如果先前失败,则执行下一个命令)将捕获失败(无输入)set
命令来检索数据。