1

How can I write to use two nested variables at once, like an array? I am trying to make a number of variables specified by the user (array indexes from 1 up to that number) and their names are also specified by the user (array name), but when I do this nothing is returned. Can anyone help me please?

echo how many people?
set /p number=
echo.
echo.
for /l %%a in (1,1,%number%) do (
    echo name of %%a person
    set /p s%%a =
    echo.
    echo.
    echo.
    if %%a==%number% (
        echo names are
        pause
        for /l %%n in (1,1,%number%) do (
            echo name %%n is %s%%a%
        )
    )
)
aschipfl
  • 33,626
  • 12
  • 54
  • 99
Evil DEvil
  • 40
  • 6
  • Besides missing delayed expansion, you must remove the _space_ in front of the `=` sign in `set /p s%%a =` for it not to become part of the variable name... – aschipfl Jan 06 '17 at 18:20
  • 1
    See [this answer](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Jan 06 '17 at 20:42

2 Answers2

1

So what you are trying to do is create a pseudo array as batch files do not have arrays natively. So you need to use delayed expansion to get your expected output.

@echo off
SetLocal EnableDelayedExpansion
echo how many people?
set /p number=
echo.
echo.
for /l %%a in (1,1,%number%) do (
    echo name of %%a person
    set /p s%%a=
    echo.
    echo.
    echo.
    if %%a==%number% (
        echo names are
        for /l %%n in (1,1,%number%) do (
            echo name %%n is !s%%n!
        )
    )
)
pause
Squashman
  • 13,649
  • 5
  • 27
  • 36
0

You are missing DelayedExpansion:

In batch a closed block of parentheseis gets calculated at once, so variable values changed within it will not be displayed using the normal %myVar% when accessed within it.

To do so however add setlocal EnableDelayedExpansion at the top of your script and change %myVar% to !myVar!.

Btw with the command @echo off you can suppress a lot of unneccessary command-line output :)

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54