简体   繁体   中英

Printing array in batch file using variable index, having trouble with delayed expansion

All I am trying is to store a string in an array and then access them using variable as index. I have tried Delayed Expansion, but I don't know what is wrong with code. Please help. The test.cmd file contains

@echo OFF
@set i=1
echo ENTER Your First Name :
setlocal enableDelayedExpansion
set /p input_value[%i%]=%=%
call:print
endlocal
@set i=2
setlocal enableDelayedExpansion

echo ENTER Your Last Name :
set /p input_value[%i%]=%=%
call:print
endlocal
:print
@echo !input_value[%i%]!
GOTO:EOF

Output:

D:\backup_app\bat>test.cmd
ENTER Your First Name :
radhe
radhe
ENTER Your Last Name :
kishan
kishan
!input_value[2]!

The last line in the output is what that is troubling me.

You need to skip over the :print procedure (an you could enable delayed expansion only to necessary code snippet) as follows:

@echo OFF
setlocal enableExtensions
@set i=1
echo ENTER Your First Name :
set /p input_value[%i%]=%=%
call:print
@set i=2

echo ENTER Your Last Name :
set /p input_value[%i%]=%=%
call:print
goto :next
:print
    setlocal enableDelayedExpansion
    echo !input_value[%i%]!
    endlocal
    GOTO:EOF
:next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM