在“for"循环中使用变量

编程入门 行业动态 更新时间:2024-10-27 10:25:28
本文介绍了在“for"循环中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码:

@echo off设置 ITER=0对于 (%*) 中的 %%i 做 (设置 ITER+=1回声%ITER%)

输出是(对于三个参数):

000

预期输出:

123

为什么我不能在 for 循环中访问更新的变量?

解决方案

在执行语句/块之前使用百分比扩展变量.因此,在您的情况下,在执行 echo %ITER% 之前将完整块扩展为常量 echo 0.变量 ITER 本身在循环中正确更新.

为了避免这种情况,您可以使用延迟扩展,这类似于百分比扩展,但只是在执行的那一刻

@echo offsetlocal EnableDelayedExpansion设置 ITER=0对于 (%*) 中的 %%i 做 (SET/a ITER+=1回声!ITER!)

I have following code:

@echo off SET ITER=0 for %%i in (%*) do ( SET ITER+=1 ECHO %ITER% )

The output is (for three arguments):

0 0 0

Expected output:

1 2 3

Why can't I access the updated variable in the for loop?

解决方案

Expansion of variables with percents is done before a statement/block is executed. So in your case the complete block is expanded before the echo %ITER% is executed, to constant echo 0. The variable ITER itself is updated in the loop properly.

To avoid this, you could use the delayed expansion, this works like percent expansion but just in the moment of execution

@echo off setlocal EnableDelayedExpansion SET ITER=0 for %%i in (%*) do ( SET /a ITER+=1 ECHO !ITER! )

更多推荐

在“for"循环中使用变量

本文发布于:2023-10-26 01:23:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!