Making CHOICE Count
Another use of CHOICE is in a counted loop. The example, LEFT.BAT, shown below returns the left "N" characters from the string provided as the first argument (%1). The second argument is a decimal number. DOS does not provide directly for a variable, numbered loop counter, but CHOICE makes it possible. The trick is to create a string that grows by one character for each pass through the loop. CHOICE is then used to determine if the length of the string is equal to the loop count. In this case, the desired portion of the string, held in the variable {Left}, is used as the counter string. As each character from the original is added, the sum of this string plus a semicolon is tested. When {Left} reaches the desired number of characters, the ERRORLEVEL returned by Choice is equal to N (stored in the environment variable {E}) and the loop is exited.

:: LEFT.BAT - A routine to return the left 'N' characters of a string. :: Revised: 18 Mar 97 :: Tom Lavedas <lavedas@pressroom.com> :: http://www.pressroom.com/~tglbatch/ :: Syntax: LEFT String N :: Result stored in environment variable {Left} :: @echo %dbgl% off if [%2]==[] %0 0 0 if '%1'=='[?' goto Loop set {Left}= set {e}=%2 if [%2]==[0] goto End > %ram%.\{t}.bat echo;;|choice /c?%1; %0; %ram%.\{t} :: :Loop { Start of counted loop processing } :: if '%2'==']?' for %%v in (del goto:End) do %%v %ram%.\{t}.bat echo;;|choice /n /c%{Left}%; > nul set {Left}=%{Left}%%2 if not errorlevel %{e}% for %%v in (shift goto:Loop) do %%v :: :: { End of counted loop processing } :: del %ram%.\{t}.bat :End :: { Display for demonstration purposes } echo For example, %{e}% characters: %{Left}% set {e}=




Top | General Notes | Homepage