J D
J D

Reputation: 15

Batch: How to prevent looping code when holding enter

So iv'e made a little something here where there will be a list of numbers like 1-10 and whichever one you type (so far only 1) will show you information (so if i type and enter 1, it will go key1=key).

However, if I type 1 and click enter, it shows me that the Key1 = key which i intended but then if I hold down Enter key, it will keep looping the Key1=Key script and the homepage one, can this be stopped?

@echo off
:T
cls

echo Home Page
echo [1] NameA
echo.
echo [e] Exit

set /p word=
if "%word%"=="1" goto aaa
if "%word%"=="e" goto eee
goto T

:aaa
cls
echo Key1 = Key
pause
goto T

:eee
exit

Upvotes: 0

Views: 187

Answers (2)

michael_heath
michael_heath

Reputation: 5372

@echo off
setlocal

:T
cls

echo Home Page
echo [1] NameA
echo.
echo [e] Exit

rem Undefine variable word before input.
set "word="

set /p "word="

rem No input = word is not set a new value, thus not defined.
if not defined word goto eee

if "%word%"=="1" goto aaa
if "%word%"=="e" goto eee
goto T

:aaa
cls
echo Key1 = Key
pause
goto T

:eee
exit

If you only press Enter at the set /p prompt, variable word is not set (a new value). If word is undefined before the set /p input, then it will be undefined after, if you only press Enter.

setlocal added to keep variables set local to the current script execution.

Upvotes: 0

Stephan
Stephan

Reputation: 56180

set /p keeps the last value, if you just press enter. You should set the variable to empty (or a default value, if you prefer):

@echo off
:loop
REM set "word="  ; for "empty"
set "word=string"
set /p "word=Enter your choice (or just ENTER for '%word%': "
echo you choosed %word%
goto :loop

May I bring your attention to the choice command, which may (or may not) be a better choice.

Upvotes: 1

Related Questions