Counter with batch

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gotouser
Posts: 7
Joined: 26 Feb 2018 07:36

Counter with batch

#1 Post by gotouser » 26 Feb 2018 07:51

Hello,
I'm new to batch and I'm just learning how to do simple things. I wanted to make a simple counter, so tht every time you type in a certain word or number, it would add 1 to the counter. I typed this into the Editor:

Code: Select all

@echo off
setlocal enabledelayedexpansion

:loop
echo test
set a COUNTER=0
set /p NUM=
if %NUM%==1 goto 1
echo !COUNTER!
pause
goto loop

:1
set /a COUNTER=!COUNTER!+1
echo !COUNTER!
pause
goto loop
This works fine, but I don't know why it does. I accidentally typed in "set a" instead of "set /a", but when I corrected it, it no longer worked and just counted up to 1, then got stuck at that number. Why does it work with "set a"?
Last edited by Squashman on 08 Mar 2018 08:17, edited 1 time in total.
Reason: MOD EDIT: Please use code tags.

gotouser
Posts: 7
Joined: 26 Feb 2018 07:36

Re: Counter with batch

#2 Post by gotouser » 26 Feb 2018 11:03

Okay, I noticed I made a pretty stupid mistake. Of course, every time it goes to loop, it resets the counter to zero. Got it now :mrgreen:

elzooilogico
Posts: 128
Joined: 23 May 2016 15:39
Location: Spain

Re: Counter with batch

#3 Post by elzooilogico » 26 Feb 2018 15:22

only a note

Code: Select all

set /a COUNTER+=1
is best practice. you don't need any expansion with set /a, and you can make one line calculations

Code: Select all

set /a counter+=1, test=counter%%3, …
.
this is always evaluated left to right, so the left variable reflects the new value of the right one

pieh-ejdsch
Posts: 240
Joined: 04 Mar 2014 11:14
Location: germany

Re: Counter with batch

#4 Post by pieh-ejdsch » 27 Feb 2018 10:26

Code: Select all

set a Counter=0
will create a varName like "a Counter" with Content is 0

Code: Select all

set Counter=0
will create a varname like "Counter" with Content is 0

Code: Select all

set /a Counter = 0
will use all Arithmetic operations to create or/and calculate with Content.

elzooilogico
Posts: 128
Joined: 23 May 2016 15:39
Location: Spain

Re: Counter with batch

#5 Post by elzooilogico » 27 Feb 2018 14:08

pieh-ejdsch wrote:
27 Feb 2018 10:26

Code: Select all

set a Counter=0
will create a varName like "a Counter" with Content is 0
Good catch! I totally miss that! :oops:

gotouser
Posts: 7
Joined: 26 Feb 2018 07:36

Re: Counter with batch

#6 Post by gotouser » 27 Feb 2018 15:00

Thank you, now I understand it :D

Post Reply