4

I have two elements in my array list in my program. How can I assign a variable to equal one of the elements?

Here's the code:

@echo off
setlocal enabledelayedexpansion
set /p string=
for /l %%a in (0,1,1000) do if not "!String:~%%a,1!"=="" set /a length=%%a+1
set i=0
:input
set str=%string:~0,1%
if "%str%"=="M" set array[i]=1000
if "%str%"=="D" set array[i]=500
if "%str%"=="C" set array[i]=100
if "%str%"=="L" set array[i]=50
if "%str%"=="X" set array[i]=10
if "%str%"=="I" set array[i]=1
set string=%string:~1%
set /a i=i+1
if %i%==%length% goto logic
goto input
:logic

I really though there was a standard way of doing this.

Ivan Spajić
  • 159
  • 3
  • 5
  • 14

1 Answers1

3

The main problem is that your code doesn't create any batch-array.
Your code create only one variable named array[i], but I suppose you want to create an array with:

array[0]=1000
array[1]=500

Then you need something like

setlocal EnableDelayedExpansion
set i=0
:inputLoop
set "str=%string:~0,1%"
if "%str%"=="M" set array[%i%]=1000
if "%str%"=="D" set array[%i%]=500
if "%str%"=="C" set array[%i%]=100
if "%str%"=="L" set array[%i%]=50
if "%str%"=="X" set array[%i%]=10
if "%str%"=="I" set array[%i%]=1
set "string=%string:~1%"
set /a i+=1
if NOT %i%==%length% goto :inputLoop

:logic
rem ** logic begins
for /L %%n in (1 1 %i%) do (
   echo !array[%%n]!
   set /a value=array[%%n]
)

And in the logic part you can see how to access an array element.

Btw. Your strlen function is a little bit slow, it could be faster with a binary search.
How to count the characters in a string with Batch?

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225