中国DOS联盟论坛

China DOS Union

-- Unite DOS · Advance DOS · Grow DOS --
Union site: www.cn-dos.net Forum site: www.cn-dos.net/forum
Guest | Log in | Register | Members | Search | China DOS Union
中国DOS联盟论坛
The time now is 2026-08-02 02:37
48,037 topics / 350,122 posts / today 2 new / 48,250 members
DOS批处理 & 脚本技术(批处理室) » Problems with using the SET command to take strings one by one. (Solved)
Printable Version  1,882 / 3
Floor1 zts59 Posted 2006-08-23 19:36
中级用户 Posts 104 Credits 387
The original Chinese text contains some content about batch code issues. The relevant translation for the part about the problematic instruction is:

The problem with the instruction `set "char0=!choice:~%n%,1!"` is that the variable name here is wrong. It should be `char` instead of `choice`. Because earlier you used `set /p char=`, so the variable to be processed should be `char` not `choice`.
Floor2 namejm Posted 2006-08-23 23:51
荣誉版主 Posts 1,737 Credits 5,226 From 成都
Suppose you have the statements correct elsewhere, but you set n=0 earlier and then don't change the value of n later, so in the statement "set "char0=!choice:~%n%,1!"", %n% is always 0, and you can only get the first character.

In fact, there is a problem with the statement "set "char0=!choice:~%n%,1!"" (is choice a typo for char?) in your code. I don't see the function of using !!; the whole code will have an error.

[ Last edited by namejm on 2006-8-23 at 23:55 ]
Floor3 3742668 Posted 2006-08-24 08:11
荣誉版主 Posts 718 Credits 2,013
Originally posted by zts59 at 2006-8-23 19:36:
set char=
set /p char= enter:
:test
set n=0
set "char0=!char:~%n%,1!"
if %char0%="" goto end
set /A n="n+1"
echo %char0%
goto test
:end
pause


Want to achieve...

1. Logical error:
The line
set n=0
is after the subsequent goto test, which will reset the value of n to 0 again. Even if all other code is correct, it will fall into an infinite loop, continuously displaying the first character.
Correct solution:
Move it in front of the test label.
2. Syntax error:
if %char0%="" goto end

Correct solution:

3. Command error:
The command to enable delayed environment variable expansion, setlocal ENABLEDELAYEDEXPANSION, is not used, resulting in the variables contained in the subsequent!! not being recognized and being treated as strings.
Correct solution:
Add setlocal ENABLEDELAYEDEXPANSION at the front.
Modify your code slightly as follows:

Used to handle strings without sensitive characters, which is basically sufficient.
Floor4 zts59 Posted 2006-08-24 08:59
中级用户 Posts 104 Credits 387
Thanks, you guys. There is indeed a typo,
and there is also a logical problem. Thanks for correcting.

Oh, and there's also an if "char0%" == "" goto end

When should we use quotes and when not?

Also, using the command to enable delayed environment variables, thank you again.
[ Contact the Union admin team - 中国DOS联盟 - Standard version ]
Sponsored by ifanr Inc | © 2001–2023