I want to display the content of an array with a prompted variable.
So, I make the following code:
::Create an array
SET country[0]=Albania
SET country[1]=Argentina
SET country[2]=Australia
SET country[3]=Austria
SET country[4]=Belgium
::Create a menu
SET /P C=Type the number of your country, then press ENTER:
SET /A C_num=%C%
ECHO.
for /L %%a in (0, 1, 59) do call ECHO %%a - %%country[%%a]%%
ECHO.
And I tried this code to display the corresponding country:
ECHO %country[!C_num!]%
However it didn't succeed in displaying the content.
Can you help me to fix it?
Hmm... well, TBH, you wouldn't need to ask the question if you did succeed...
So - to solve your problem, we'd need to know a little more The first is about how your file starts. The normal start to a batch file is
which turns default command-echoing off to not clutter the screen and then establishes a "local environment" which has the useful property that when the batch ends, all variables modified when running the batch are restored to their original values (those they had when the batch started). This prevents a subsequent batch that is run in the same session from inheriting the modifications made by this batch.
Next issue is the format of your
setstatements. Useset "var=value"for setting string values - this avoids problems caused by trailing spaces. Don't assign"or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier. If the syntaxset var="value"is used, then the quotes become part of the value assigned.And a little quirk:
SET /P "var=Prompt"does not changevarif Enter alone is pressed. Consequently, ifvaris originally empty, it remains empty. With the quotes as shown, you can put a space at the end ofPrompt.I'd suggest it would be better if you displayed your list before you ask for a selection - it might just make it a little easier.
You have (potentially) a great long list to display, some entries in which are empty. You could modify your
%%aloop to…do if defined country[%%a] echo …which may shorten the dispayed list by not showing anycountry[?]that has not been defined.Variables in batch are always strings. The mathematical functions available convert the variable contents to numerics to perform the calculations, then back again to strings to be assigned or
echoed. Consequently, "converting"CtoC_numactually achieves nothing.country[%C%]is exactly the same ascountry[%C_num%].You haven't told us what you get when you try
ECHO %country[!C_num!]%. You need a thorough understanding of Delayed expansionSo - you need to first invoke
delayedexpansionand thenECHO !country[%C_num%]!On the other hand, you could try adapting this: Menu with 3 columns which uses
choice- preferred because it obviates processing of potential random user-input.