For won't run if errorlevel's too high

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
john924xps
Posts: 65
Joined: 08 Jun 2012 07:48

For won't run if errorlevel's too high

#1 Post by john924xps » 30 Dec 2012 07:56

Hi!
I've been trying to create a program which allows you to type up a piece of text with asterixes in place of the letters and numbers. This is my code

Code: Select all

@echo off
title %~n0
color 0b
set chars=a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 0
set text=
set in=
set asterix=

:main
cls
echo Current Value: %text%
choice /c %chars: =% /n /m "Text: %asterix%"
::debug
echo errorlevel: %errorlevel%
pause
::bug is here. if errorlevel higher than 32, then it wont execute
for /f "tokens=%errorlevel%" %%G in ("%chars%") do (
echo if you see this message, then the loop is successful.
pause
set text=%text%%%G)
set asterix=%asterix%*
goto :main

I've tested everything; the letters that aren't displayed have their own proper errorlevel, but if the errorlevel is 33 (number 6) or higher, then the for loop will not execute. It's really annoying :(

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: For won't run if errorlevel's too high

#2 Post by abc0502 » 30 Dec 2012 08:34

That is strange, as i was just playing with the RTrim Function and it also doesn't trim characters from the right side that is over 32 :?

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: For won't run if errorlevel's too high

#3 Post by dbenham » 30 Dec 2012 08:47

That has nothing to do with ERRORLEVEL. FOR /F simply cannot parse more than 31 tokens. (your code fails at 32, not 33).

A simple solution for your case is to use a substring operation to extract the relevant character instead of using FOR /F.

It is easiest if you restructure your string so that the position index matches your choice values. The substring requires two levels of variable expansion, one for ERRORLEVEL and one for CHARS. The most efficient solution is to use delayed expansion.

Code: Select all

@echo off
setlocal enableDelayedExpansion
title %~n0
color 0b
set "chars= abcdefghijklmnopqrstuvwxyz1234567890"
set "text="
set "in="
set "asterix="

:main
cls
echo Current Value: %text%
choice /c %chars: =% /n /m "Text: %asterix%"
set "text=%text%!chars:~%errorlevel%,1!"
set "asterix=%asterix%*"
goto :main


It can be done less efficiently without delayed expansion. With this application, the less efficient method works just as well.

Code: Select all

@echo off
title %~n0
color 0b
set "chars= abcdefghijklmnopqrstuvwxyz1234567890"
set "text="
set "in="
set "asterix="

:main
cls
echo Current Value: %text%
choice /c %chars: =% /n /m "Text: %asterix%"
call set "text=%text%%%chars:~%errorlevel%,1%%"
set "asterix=%asterix%*"
goto :main


Dave Benham

Post Reply