0

I'm finishing off my program, and I've got a basic menu:

echo [1] - New Log Entry
echo [2] - Read Log Entry
echo [3] - Clear Log
echo [4] - Exit
set /p menu=Number: 
if %menu%==1 goto NewLog
if %menu%==2 goto Readlog
:::and so on

But I want it to be so that when you type in one of the numbers, it automatically enters the number they put.

I think I've seen it done before but I'm not too sure.

awillers55
  • 35
  • 1
  • 5

1 Answers1

0

The command CHOICE can be used for taking one of predefined options.

@echo off
:Menu
cls
echo/
echo [1] - New log entry
echo [2] - Read log entry
echo [3] - Clear log
echo [4] - Exit
echo/
choice /C 1234 /N /M "Your choice: "
echo/
if errorlevel 4 goto :EOF
if errorlevel 3 goto ClearLog
if errorlevel 2 goto ReadLog

rem User has taken first choice as being the only remaining choice.

echo Creating new log entry ...
echo/
pause
goto Menu

:ReadLog
echo Reading log entry ...
echo/
pause
goto Menu

:ClearLog
echo Clearing log ...
echo/
pause
goto Menu

The usage of CHOICE is much better than set /P variable=prompt text for such tasks as the user must press one of the offered keys and execution immediately continues once an offered key is hit by the batch file user. set /P gives the user the freedom to enter anything from not entering anything at all up to a very long string containing characters which might result in a syntax error on evaluation of the environment variable value if not extra code is written to make sure that batch file works even for any invalid user input.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • choice /?
  • cls /?
  • echo /?
  • goto /?
  • if /?
  • pause /?

See also the web pages:

Mofi
  • 46,139
  • 17
  • 80
  • 143