JohnBatch
JohnBatch

Reputation: 37

How to use the choice command?

I need the choice command to do the same thing as this block of code:

set /p start= Select Mode:
if %start% == 1 goto money
if %start% == 2 goto payouts
if %start% == 3 goto tutorial
if %start% == 4 exit /b

I have been trying for quite some time now and cannot figure it out Thanks in advance!

Upvotes: 1

Views: 7425

Answers (3)

Aacini
Aacini

Reputation: 67256

The simplest solution is not check the value of errorlevel at all, but directly use it in a goto command. In this way, you avoid the usual series of if commands, so the code is simpler.

choice /C 1234 /M "Select Mode: "
goto option-%errorlevel%

The rest of the code shoud be like this:

:option-1 money
echo Money
goto loop

:option-2 payouts
echo Payouts
goto loop

:option-3 tutorial
echo Tutorial
goto loop

:option-4
exit /B

Upvotes: 7

Compo
Compo

Reputation: 38718

An alternative to the answer by fvu, is to use the %ErrorLevel% variable as Squashman suggested:

Choice /C 1234 /M "Select Mode: "
If %ErrorLevel%==1 GoTo money
If %ErrorLevel%==2 GoTo payouts
If %ErrorLevel%==3 GoTo tutorial
Exit/B
[:money | :payouts | :tutorial]

Upvotes: 2

fvu
fvu

Reputation: 32973

Using the command choice like this

choice /c 1234 /M "Select Mode: "

upon exit, errorlevel will be set to the index (starting with 1) of the selected choice. For acting upon the errorlevel it's important to remember that "if errorlevel n" traps not only n, but also all higher values, meaning that they need to be specified in reverse

 if errorlevel 4 goto exit
 if errorlevel 3 goto tutorials
 if errorlevel 2 goto payout
 if errorlevel 1 goto money

Upvotes: 5

Related Questions