Loop That Stores User Input In X Variables

August 28, 2009 at 12:52:41
Specs: Windows Vista Home P, Core 2 Quad 8200/6gb
I am trying run a loop X amount of times, and prompt for a string each time and store it in a separate variable for each prompt. Here is what I have:

@ECHO OFF
SETLocal EnableDelayedExpansion

SET /P Number=

:LOOP

set /A Count+=1

IF !Count! gtr !Number! GOTO :eof

SET /P File!Count!=Name of File!Count!?-

Goto LOOP

It loops through and asks me for all the file names, but it doesn't store the values in the variables I want(file1, file2, etc.) I suspect that you can't set a variable name that contains a variable which leads me the real problem: I don't have a clue how to set a "variable" number of variables.


See More: Loop That Stores User Input In X Variables

Report •


#1
August 28, 2009 at 13:14:53
What happens when you try? Are the file variables empty? If so, it's because you're using SETLOCAL and GOTO :EOF

Report •

#2
August 28, 2009 at 14:26:00
Oh! Yeah, your right. I was changing someone else's loop code for another purpose and I didn't realize what :eof did. So, now I get the variables set correctly.

Which brings me to another thing I don't know how to do; run a command on all those variables. For simplicity, how would I ECHO each "File" variable that is created in the loop into a text file?

@ECHO OFF
SETLocal EnableDelayedExpansion

SET /P Number=

:LOOP

set /A Count+=1

IF !Count! gtr !Number! GOTO :EndLoop

SET /P File!Count!=Name of File!Video!?-

Goto LOOP

:EndLOOP


Report •

#3
August 28, 2009 at 15:02:39
If you are not inside a block (e.g. a FOR loop or anything that
involves surrounding multiple commands in parentheses) then
the following should work:

echo !File%Count%!

(Note that the "%" expansion happens before the "!".)
If you want to iterate over all variables from 1 to Number:

for /l %%i in (1,1,!Number!) do (
   echo !File%%n!
)


Report •

Related Solutions

#4
August 28, 2009 at 15:23:21
Thanks a lot. That's pretty ironic. I tried %File!Count!% instead of !File%Count%! and the /l switch of FOR, but I guess I didn't do it right. Do you have to use %%i and %%n?

Report •

#5
September 2, 2009 at 06:36:55
Sorry, that was a typo. I meant %%i both times, i.e. echo !File%%i!

Report •


Ask Question