Page 1 of 1

For won't run if errorlevel's too high

Posted: 30 Dec 2012 07:56
by john924xps
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 :(

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

Posted: 30 Dec 2012 08:34
by abc0502
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 :?

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

Posted: 30 Dec 2012 08:47
by dbenham
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