0

I want to echo one element that the user choses from a premade array. So if the user writes a 2, I want to echo the second element of the array.

This is my code simplified. I have tried using the user input directly and converting it to int, but none of those options work.

@echo off
setlocal EnableDelayedExpansion

set test[1]=a
set test[2]=b
set test[3]=c
set test[4]=d

set /p number="Select array element: "
set /a numberAux=!number!+0

echo: 1.: !test[2]!
echo: 2.: !test[%%number]!
echo: 3.: !test[%%numberAux]!

timeout /t 3 /nobreak > NUL

endlocal

This is the output:

Select array element: 2
 1.: b
 2.:
 3.:

  • 1
    Try `!test[%number%]!` and `!test[%numberAux%]!` Please consider choice which is designed for this task. Use the search facility for [batch-file] choice eg Gerhard's example https://stackoverflow.com/a/58370914/2128947 or see the documentation - `choice /?` from the prompt. – Magoo May 08 '23 at 21:34
  • `echo: 2.: !test[%number%]!` or `call echo: 2.: %%test[%number%]%%`. See [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini May 09 '23 at 06:17
  • 1
    @Magoo This actually works. I thought I had already tried that, but it seems I didn't. Thanks! – Roberto Fernández May 09 '23 at 10:36
  • 1
    @Aacini The first one is the solution to my problem. The second one just prints: `2.: %test[2]%` – Roberto Fernández May 09 '23 at 10:39
  • I just tested the second one here and it works... Are you sure you included the `call` command first? – Aacini May 09 '23 at 18:06

1 Answers1

0

As @Magoo suggested, the answer is simply using !test[%number%]!, this works both directly with the user input and when converting the input to integer. I was confused with other answers that use the [%%number] when printing the contents of an array using a for loop.

So the corrected code would be:

set test[1]=a
set test[2]=b
set test[3]=c
set test[4]=d

set /p number="Select array element: "
set /a numberAux=!number!+0

echo: 1.: !test[2]!
echo: 2.: !test[%number%]!
echo: 3.: !test[%numberAux%]!

timeout /t 3 /nobreak > NUL

endlocal

And this would correctly print:

Select array element: 2
 1.: b
 2.: b
 3.: b
  • ` converting the input to integer` - `cmd` has only one sort of variable: STRING. (yes, `set /a` internally converts the arguments to INT32 to be able to do math - but it takes STRING for input and outputs STRING) - (just to clarify, I see your point) – Stephan May 09 '23 at 13:13
  • I am pretty sure that there is not a single _working_ example that uses `[%%number]`... Could you post the link to any of such answers? (Perhaps you confuse it with `[%%n]` where `%%n` is a `for` replaceable parameter) – Aacini May 09 '23 at 18:12