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%
        )
    )
)
2
  • 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... Commented Jan 6, 2017 at 18:20
  • 1
    See this answer Commented Jan 6, 2017 at 20:42

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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 :)

3 Comments

thanks for the help but can you please explain %myVar% !myVar! i didn't understand what should i replace
If you have for example %number% change it to !number! so change % to !.
i did nothing happend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.