How to do math in batch-file - batch-file

I have been having troubles with batch-codes that I would expect to work, but don't...
Below is what I have written...
#echo off
cls
:loop
set /p "input=Input a number: "
set /a "number=%input%" 2>nul
REM check if input valid
if "%input%" NEQ "%number%" (
cls
Echo Please Enter a valid number! &Echo.&Echo.
goto :loop
)
Set /a Even=number%%2
if %Even% EQU 0 (
Echo Substituting Even Number in: x / 2
Echo set /p"=(%number%) / 2 = "
set /a answer=number/2
) Else (
Echo Substituting Odd Number in: 3x - 1
<nul set /p"=3(%number%)-1 = "
set /a answer=number*3
set /a answer=answer-1
)
Echo %answer%
Echo.
Echo.
goto :loop
Echo Unexpected Error . . .
pause
Exit
Whenever I input a number into the console, it does the math, like I want it to, but prints the number -1, and every time i input another number, the number goes to -2, -3, -4, so on.

Put a setlocal enableextensions at the beginning after the #echo off, e.g.
#echo off
setlocal enableextensions
cls
Also, I think you would also need to use delayed variable expansion (usually denoted by !var!), which would change your script above to something like this:
#echo off
setlocal enableextensions enabledelayedexpansion
cls
:loop
set /p "input=Input a number: "
set /a number=!input! 2>nul
REM check if input valid
if "!input!" NEQ "!number!" (
cls
Echo Please Enter a valid number!
Echo.
Echo.
goto :loop
)
REM Make sure that it is an integer put in (just in case)
set /a int=!number! %% 1
if "!input!" NEQ "!int!" (
cls
Echo Please Enter a valid number!
Echo.
Echo.
goto :loop
)
Set /a Even=!number! %% 2
if !Even! EQU 0 (
Echo Substituting Even Number in: x / 2
set /a answer=!number! / 2
) Else (
Echo Substituting Odd Number in: 3x - 1
set /a answer=!number! * 3 - 1
)
Echo !answer!
Echo.
Echo.
goto :loop
I also would like to point out that I also fixed a few other bugs (set /p isn't of any use in this script at all, especially in where it is used, and also you need the modulus to find even/odd).

Related

Convert number to different number in batch file

This must be very basic but i can't seem to find a way to get this done
my batch script goes like this:
#echo off
echo Type In Desired Volume And Press Enter
echo.
echo 0 = 0 %%
echo 1 = 100 %%
echo 0.10 = 10 %%
echo 0.65 = 65 %%
echo.
set /p input=
echo %input% > "C:\SetVol\Source\Volume.txt
I want to make it more user friendly by letting the user input a number between 0 and 100 instead of, for example, 0.10 for 10% audio volume. But i still need to output the 0.10 to a textfile if the user enters 10.
Google appears to longer be my best friend and we cant seem to communicate on this.
If anybody could help me get starter that would be great.
A simple way is to convert the input number to the requested output format.
One step is to prefix the input with 0.
set /p input=[Enter volume in %%]:
set "output=0.%input%"
echo %input% > "C:\SetVol\Source\Volume.txt
But this would fails for one digit values like 2%, becomes 0.2 instead of 0.02.
This can be fixed with prefix each number with 00 and take the last three digits and add a dot between.
set /p input=[Enter volume in %%]:
set "temp=00%input%"
set "output=%temp:~-3,1%.%temp:~-2%"
echo %output% > "C:\SetVol\Source\Volume.txt
You can use choice in a loop to make a key based 'slider', and then modifiy the variable value to include a 0. prefix or be 1 using an if condition:
#Echo off
set "volume=50"
:Volume
cls
Echo( Current volume: %Volume%%% [I]ncrease [D]ecrease [C]ontinue
For /f "delims=" %%G in ('Choice /N /C:IDC')Do (
If "%%G"=="I" If not %Volume% GEQ 100 Set /A Volume+=1
If "%%G"=="D" If not %Volume% LEQ 0 Set /A Volume-=1
If not "%%G"=="C" Goto :Volume
)
IF %volume% Equ 100 ( Set "Volume=1" )Else If %volume% LSS 10 (
Set "Volume=0.0%Volume%"
) Else Set "Volume=0.%Volume%"
:#your script here
For NTFS systems, a variant that stores the last set volume in an alternate data stream and reasigns the last value on return:
#Echo off
set "volume=50"
For /f "Usebackq delims=" %%G in ("%~f0:Volume")Do Set "%%G"
:Volume
cls
Echo( Current volume: %Volume%%% [I]ncrease [D]ecrease [C]ontinue
For /f "delims=" %%G in ('Choice /N /C:IDC')Do (
If "%%G"=="I" If not %Volume% GEQ 100 Set /A Volume+=1
If "%%G"=="D" If not %Volume% LEQ 0 Set /A Volume-=1
If not "%%G"=="C" Goto :Volume
)
Set Volume >"%~f0:Volume"
IF %volume% Equ 100 ( Set "Volume=1" )Else If %volume% LSS 10 (
Set "Volume=0.0%Volume%"
) Else Set "Volume=0.%Volume%"
:#your script here
Note: by using this method of input, invalid input cannot be entered.
Figured out a way to use the choice input, if anyone has a more neat or different way to do this please let me know... 291 more lines to edit...
#echo off
echo Choose Audio Volume 0-100 %%
:choice
set /P c=
if /I "%c%" EQU "0" goto :0
if /I "%c%" EQU "1" goto :1
if /I "%c%" EQU "2" goto :2
goto :choice
:0
echo 0 > C:\users\%username%\desktop\numbertest.txt
echo You chose %c% %%
pause
exit
:1
echo 0.01 > C:\users\%username%\desktop\numbertest.txt
echo You chose %c% %%
pause
exit
:2
echo 0.02 > C:\users\%username%\desktop\numbertest.txt
echo You chose %c% %%
pause
exit

CMD opens and closes all of a sudden. (batch file coding)

This is a simple calculator:
#ECHO OFF
TITLE Simple Calculator
ECHO if you want to add press 1,subtract 2,multiply 3 and divide 4
set /a selection =
if %selection%== "1" goto add
if %selection%== "2" goto sub
if %selection%== "3" goto multiply
if %selection%== "4" goto divide
:add
ECHO Type the first number you wish to add:
SET /P Numadd1=
ECHO Type the second number you want to add to the first number:
SET /P Numadd2=
ECHO.
SET /A Ansadd=%Numadd1%+%Numadd2%
ECHO The result is: %Ansadd%
ECHO.
ECHO Press any key to exit.
PAUSE>nul
:sub
ECHO Type the first number you wish to subtract with:
SET /P Numsub1=
ECHO Type the second number you want to subtract from %Numsub1%:
SET /P Numsub2=
ECHO.
SET /A Ansub=%Numsub1%-%Numsub2%
ECHO The result is: %Ansub%
ECHO.
ECHO Press any key to exit.
PAUSE>nul
:multiply
ECHO Type the first number you wish to multiply:
SET /P Nummul1=
ECHO Type the second number you want to multiply with the first number:
SET /P Nummul2=
ECHO.
SET /A Ans=%Nummul1%+%Nummul2%
ECHO The result is: %Ansmul%
ECHO.
ECHO Press any key to exit.
PAUSE>nul
:divide
ECHO Type the first number you wish to divide:
SET /P Numdiv1=
ECHO Type the second number you want to divide with the first number:
SET /P Numdiv2=
ECHO.
SET /A Ansdiv=%Numdiv1%+%Numdiv2%
ECHO The result is: %Ansdiv%
ECHO.
ECHO Press any key to exit.
PAUSE>nul
May I know what is the problem with this and the correct code?
There were too many issues to mention in the comment section so please take a look at this example against yours to see if you can identify them:
#ECHO OFF
TITLE Simple Calculator
SET /P "Selection=Enter + to Add, - to Subtract, * to Multiply or / to Divide: "
IF "%Selection%"=="+" GOTO Add
IF "%Selection%"=="-" GOTO Subtract
IF "%Selection%"=="*" GOTO Multiply
IF "%Selection%"=="/" GOTO Divide
GOTO :EOF
:Add
SET /P "Numadd1=Enter an addend: "
SET /P "Numadd2=Enter another addend: "
SET /A Ansadd=Numadd1+Numadd2
ECHO.
ECHO The sum is: %Ansadd%
ECHO.
PAUSE
GOTO :EOF
:Subtract
SET /P "Numsub1=Enter the minuend: "
SET /P "Numsub2=Enter the subtrahend: "
SET /A Ansub=Numsub1-Numsub2
ECHO.
ECHO The difference is: %Ansub%
ECHO.
PAUSE
GOTO :EOF
:Multiply
SET /P "Nummul1=Enter a factor:"
SET /P "Nummul2=Enter another factor: "
SET /A Ansmul=Nummul1*Nummul2
ECHO.
ECHO The product is: %Ansmul%
ECHO.
PAUSE
GOTO :EOF
:Divide
SET /P "Numdiv1=Enter the dividend: "
SET /P "Numdiv2=Enter the divisor: "
SET /A Ansdiv=Numdiv1/Numdiv2
ECHO.
ECHO The quotient is: %Ansdiv%
ECHO.
PAUSE
Ideally you should make sure that none of your variables have existing values at the start of the script and check that the entered values are compatible/validated before using them too!
Edit
You could probably make the code shorter too:
#ECHO OFF
TITLE Simple Calculator
FOR %%A IN (Operator Integer1 Integer2 Result) DO SET "%%A="
SET /P "Operator=Enter + to Add, - to Subtract, * to Multiply or / to Divide: "
IF DEFINED Operator (SET "Operator=%Operator:~,1%") ELSE GOTO :EOF
ECHO(%Operator%|FINDSTR /L "+ - * /">NUL||GOTO :EOF
SET /P "Integer1=Enter your starting integer: "
SET /P "Integer2=Now the other integer: "
SET /A Result=Integer1 %Operator% Integer2
ECHO(
ECHO The Answer is: %Result%
ECHO(
PAUSE
These two lines
ECHO if you want to add press 1,subtract 2,multiply 3 and divide 4
set /a selection =
should be:
set /p selection=if you want to add press 1,subtract 2,multiply 3 and divide 4:
There are a few errors in your code, including the math. Try and take a look at my code and compare it with yours.
#ECHO OFF
TITLE Simple Calculator
echo If you want to add press 1, subtract 2, multiply 3 and divide 4
set /p selection=
if "%selection%"=="1" goto add
if "%selection%"=="2" goto sub
if "%selection%"=="3" goto multiply
if "%selection%"=="4" goto divide
:add
ECHO Type the first number you wish to add:
SET /P Numadd1=
ECHO Type the second number you want to add to the first number:
SET /P Numadd2=
SET /A Ans=%Numadd1%+%Numadd2%
goto end
:sub
ECHO Type the first number you wish to subtract with:
SET /P Numsub1=
ECHO Type the second number you want to subtract from %Numsub1%:
SET /P Numsub2=
SET /A Ans=%Numsub1%-%Numsub2%
goto end
:multiply
ECHO Type the first number you wish to multiply:
SET /P Nummul1=
ECHO Type the second number you want to multiply with the first number:
SET /P Nummul2=
SET /A Ans=%Nummul1%*%Nummul2%
goto end
:divide
ECHO Type the first number you wish to divide:
SET /P Numdiv1=
ECHO Type the second number you want to divide with the first number:
SET /P Numdiv2=
SET /A Ans=%Numdiv1%/%Numdiv2%
:end
ECHO.
ECHO The result is: %Ans%
ECHO.
ECHO Press any key to exit.
PAUSE>nul

CMD add every variable generated to a list

I know I can write an echo > C:/Folder/name.txt
But I have a generator to make 2 number for Cord and can't figure out a quick way to make a one line echo > with all the points
for shortness I'll simplify my code because the current code is not the issue
Echo off
Setlocal EnableDelayedExpansion
set R=1
set Number=1
:Loop
if %R% EQU 1 (set /p Max=How many Max Points? ) Else(
echo.)
set /p PX%number%=What is PointX%number%?
set /p PY%number%=What is PointY%number%?
if %Number% GEQ %Max% (goto :fin) Else(
set /a Number=%Number%+1 & set R=2 & Goto :loop)
This Is what Im trying to Optimize
:fin
echo (%PX1%,%PY1%),(%PX2%,%PY2%),(%PX3%,%PY3%) ... Ect >C:Folder/File.txt
Is there any way to make all the generated numbers on 1 line
Credit to Squashman for the Answer - Thank you!
Correct Code:
Echo off
Setlocal EnableDelayedExpansion
set R=1
set Number=1
set Line=Test
:Loop
if %R% EQU 1 (set /p Max=How many Max Points? ) Else (
echo.)
set /p PX%number%=What is PointX%number%?
set /p PY%number%=What is PointY%number%?
set line=%line%(!PX%number%!,!PY%number%!),
if %Number% GEQ %Max% (goto :fin) Else (
set /a Number=%Number%+1 & set R=2 & Goto :loop)
:fin
echo %Line:~0,-1% >C:Folder/File.txt
Credit to Squashman for the Answer - Thank you!
The logic is so much simpler if you get the max point count before the loop. And the FOR /L loop can auto increment your counter and eliminate the need for GOTO.
#echo off
setlocal enableDelayedExpansion
set /p "cnt=How many points? "
set "ln="
for /l %%N in (1 1 %cnt%) do (
echo(
set /p "PX%%N=What is PointX%%N? "
set /p "PY%%N=What is PointY%%N? "
set "ln=!ln!(!PX%%N!,!PY%%N!),"
)
echo(
echo !ln:~0,-1!

Only accept numeric characters in batch file input

I am making a game from a batch file and one of the inputs can accept any character (~!##$%^&*()`) and any other. Is there any way to look for any character other than numbers and use the GOTO command? This is my script so far:
set /p guess=
echo "%guess%"|findstr /L "[a-z][A-Z]~`!##$%^&*()-_=+\^|^^;:"',<.>/?*"
if %errorlevel% == 0 goto Invalid_Number
if %guess% == %number% goto Correct
... everything else here ...
:Invalid_Number
echo Invalid Number. Input must be a number
pause
Is there any way to make this work, all it says is Access Denied, I am testing this on a school computer though, it might not work.
Put this at the bottom of your script:
:isInt <str>
for /f "delims=0123456789" %%a in ("%1") do exit /b 1
exit /b 0
Then to invoke it, do
call :isInt %guess% && success || fail
Here's a more complete example:
#echo off
setlocal
set /a rand = %RANDOM% %% 10 + 1
:begin
set /P "guess=Guess a number between 1 and 10: "
call :isInt %guess% || goto invalid
if %guess% gtr 0 if %guess% lss 11 (
if %guess% equ %rand% (
echo Lucky guess!
exit /b
) else (
echo Oooh, so close. Try again.
goto begin
)
)
:invalid
echo Please enter a valid integer between 1 and 10.
goto begin
:isInt <str>
for /f "delims=0123456789" %%a in ("%1") do exit /b 1
exit /b 0
This is the same basic idea as MC ND's solution, but instead of using the for statement to unset %guess%, it sets %errorlevel% and stops looping at the first non-numeric character. This makes it infinitesimally more efficient. :)
And with either success or fail, I like to use conditional execution (the && and || stuff).
:ask
set /p "guess=?" || goto :ask
setlocal enabledelayedexpansion
for /f "delims=0123456789" %%a in ("!guess!") do set "guess="
endlocal & set "guess=%guess%"
if not defined guess (
echo invalid input
goto ask
)
echo valid input
The basic idea behind the test is to use the numbers as delimiters in a for /f command, so they are removed from the input. If anything remains it is not a number and the code in the do clause is executed.
The delayedexpansion is enabled/disabled to handle problematic characters (specially double quotes) that could be typed in the input field.
May I suggest you a different, better approach? Instead of read any line and then check if it contains a number, your program may directly read a number, so the checking is not necessary. The way to do that is emulating SET /P command via a subroutine. This way, you may add additional constraints to the input, like read a maximum number of digits, for example.
#echo off
rem Read a number emulating SET /P command
rem Antonio Perez Ayala
setlocal
rem Define the following variable before call InputNumber subroutine
set "thisFile=%~F0"
call :InputNumber number="Enter a number of up to 5 digits: " 5
echo Number read: %number%
goto :EOF
:InputNumber var="prompt" [digits]
setlocal EnableDelayedExpansion
rem Initialize variables
if "%~3" equ "" (set numDigits=9) else set "numDigits=%3"
set "digits=0123456789"
for /F %%a in ('copy /Z "%thisFile%" NUL') do set "CR=%%a"
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
rem Show the prompt and start reading
set /P "=%~2" < NUL
set "input="
set i=0
:nextKey
set "key="
for /F "delims=" %%a in ('xcopy /W "%thisFile%" "%thisFile%" 2^>NUL') do if not defined key set "key=%%a"
rem If key is CR: terminate input
if "!key:~-1!" equ "!CR!" goto endRead
rem If key is BS: delete last char, if any
set "key=!key:~-1!"
if "!key!" equ "!BS!" (
if %i% gtr 0 (
set /P "=!BS! !BS!" < NUL
set "input=%input:~0,-1%"
set /A i-=1
)
goto nextKey
)
rem If key is not a digit: ignore it
if "!digits:%key%=!" equ "%digits%" goto nextKey
rem If can not accept more digits: ignore it
if %i% equ %numDigits% goto nextKey
rem Else: show and accept the digit
set /P "=%key%" < NUL
set "input=%input%%key%"
set /A i+=1
goto nextKey
:endRead
echo/
endlocal & set "%~1=%input%"
exit /B
You may also add any other processing to the input line, like show asterisks instead of digits, etc. For a large example on this topic, see this post

How to check a string does not start with a number in Batch?

How can I check that the first character of a string is a letter and so that it is not a number, or rather a cipher? There are no spaces or special characters in this string.
#ECHO OFF
SETLOCAL
SET /a num=5678
CALL :initnum
SET "num=hello"
CALL :initnum
SET "num=4ello"
CALL :initnum
SET "num=hell0"
CALL :initnum
SET "num=he8lo"
CALL :initnum
SET "num="
CALL :initnum
ECHO(==============
SET /a nam=7654
SET "nem=hello"
SET "nim=4ello"
SET "nom=hell0"
SET "num=he8lo"
SET "nzm="
CALL :initnum2 nam
CALL :initnum2 nem
CALL :initnum2 nim
CALL :initnum2 nom
CALL :initnum2 num
CALL :initnum2 nzm
GOTO :EOF
:initnum
IF NOT DEFINED num ECHO NUM is empty, so it doesn't begin with a numeric&GOTO :EOF
FOR /l %%a IN (0,1,9) DO IF %num:~0,1%==%%a ECHO %num% Begins with numeric&GOTO :EOF
ECHO %num% Does NOT begin with a numeric
GOTO :eof
:initnum2
IF NOT DEFINED %1 ECHO %1 is empty, so it doesn't begin with a numeric&GOTO :EOF
CALL SET "$1=%%%1%%"
FOR /l %%a IN (0,1,9) DO IF %$1:~0,1%==%%a ECHO %1 (%$1%) Begins with numeric&GOTO :EOF
ECHO %1 (%$1%) Does NOT begin with a numeric
GOTO :eof
You should be able to get what you want from this demo.
#echo off
setlocal enableextensions disabledelayedexpansion
set "var=1hello"
for /f "tokens=* delims=0123456789" %%a in ("%var%") do (
if not "%%a"=="%var%" echo var starts with a number
)
If the var contents starts with a number, the token/delim management in the for command will remove it.
edited just to include the usual (included the previous code) and some less used options just in case someone is interested
#echo off
setlocal enableextensions disabledelayedexpansion
set "var=1hello"
echo(%var%
rem Option 1 - Use the for command to tokenize the string
rem A dot is added to handle empty vars
for /f "tokens=* delims=0123456789" %%a in ("%var%.") do (
if not "%%a"=="%var%." (
echo var starts with a number
) else (
echo var does not start with a number
)
)
rem Option 2 - Use set arithmetic and detect errors
rem This will fail if the string starts with + or -
set "%var%_=0"
set /a "test=%var%_" 2>nul
if not errorlevel 1 (
echo var does not start with a number
) else (
echo var starts with a number
)
rem Option 3 - Use substring operations and logic operators
set "test=%var%."
if "%test:~0,1%" GEQ "0" if "%test:~0,1%" LEQ "9" set "test="
if defined test (
echo var does not start with a number
) else (
echo var starts with a number
)
rem Option 4 - Use findstr
rem This is SLOW as findstr needs to be executed
echo(%var%|findstr /b /r /c:"[0-9]" >nul && (
echo var starts with a number
) || (
echo var does not start with a number
)
I think this is the simplest way:
#echo off
setlocal EnableDelayedExpansion
set digits=0123456789
set var=1something
if "!digits:%var:~0,1%=!" neq "%digits%" (
echo First char is digit
) else (
echo First char is not digit
)
The first character of var is tried to be removed from digits string. If such a char was a digit, digits string change; otherwise, digits string remains the same.
#echo off
setlocal
set "the_string=a23something"
for /l %%a in (%the_string% ; 1 ; %the_string%) do set "cl_string=%%~a"
if %the_string:~0,1% neq 0 if "%cl_string%" equ "0" (
echo does not start with number
) else (
echo starts with number
)
endlocal
Another approach is with FINDSTR which eventually will be slower as it is an external for cmd.exe command.
#echo off
set "the_string=something"
echo %the_string%|findstr /b /r "[0-9]" >nul 2>&1 && (
echo starts with number
) || (
echo does not start with number
)
This will work in your situation:
echo %variable%|findstr "^[a-zA-Z]" >nul && echo it starts with an alpha character
Using findstr with regexp :
#echo off
set "$string=2toto"
echo %$string:~0,1%|findstr /i "^-*0*x*[0-9][0-9]*$">nul && echo is NUM || echo Is not NUM
in place of echo is NUM or echo is not NUM you can use a goto to redirect your script the way you want it.
#echo off
set "$string=2toto"
echo %$string:~0,1%|findstr /i "^-*0*x*[0-9][0-9]*$">nul && goto:isnum || goto:isnotnum
:isnum
echo is NUM
exit/b
:isnotnum
echo is not NUM
You have to set the string as a variable; in this way you are able to extract substrings from a main string. Here is an example:
#echo off
set EXAMPLESTRING=12345abcde
set FIRSTCHARACTERSTRING=%EXAMPLESTRING:~0,1%
The result of this short script should be 1 in this case.
Then, you can set a series of conditions to verify whether the first character is a number or not:
if %FIRSTCHARACTERSTRING%==0 goto NUMBER
if %FIRSTCHARACTERSTRING%==1 goto NUMBER
if %FIRSTCHARACTERSTRING%==2 goto NUMBER
if %FIRSTCHARACTERSTRING%==3 goto NUMBER
if %FIRSTCHARACTERSTRING%==4 goto NUMBER
if %FIRSTCHARACTERSTRING%==5 goto NUMBER
if %FIRSTCHARACTERSTRING%==6 goto NUMBER
if %FIRSTCHARACTERSTRING%==7 goto NUMBER
if %FIRSTCHARACTERSTRING%==8 goto NUMBER
if %FIRSTCHARACTERSTRING%==9 goto NUMBER
goto LETTER
:NUMBER
echo The first character is a number!
goto EOF
:LETTER
echo The first character is a letter!
goto EOF
Maybe this is not the most efficient solution but it works fine and it is easier to understand.

Resources