Here is your batch code with using delayed expansion and indents as wisely suggested by rojo:
@echo off
title Calculator
setlocal EnableExtensions EnableDelayedExpansion
:Begin
echo Press 1 for "+"
echo Press 2 for Exit
echo/
set "input="
set /P "input=Please choose your option: "
if "!input!"=="1" (
echo/
set /P "num1=Please enter first number: "
set /P "num2=Please enter second number: "
set /A ans=num1+num2
echo Your answer is !ans!
pause
cls
goto Begin
)
if "!input!"=="2" (
echo/
echo Thanks^^!
echo/
pause
exit /B
)
echo Invalid input^^!
echo/
pause
echo/
goto Begin
Variable input
is always cleared before user is asked because otherwise the user could just hit key RETURN or ENTER to keep current value of variable input
.
Delayed expansion is used on checking user input against 1
or 2
in case of user enters a character which would result in a syntax error on execution with not using delayed expansion. Better would be nevertheless the usage of command choice
for first user prompt.
For an expression evaluated on runtime by using set /A
the environment variables can be specified directly without being expanded at all. So instead of using
set /A ans=%num1%+%num2%
or
set /A ans=!num1!+!num2!
it is enough to write
set /A ans=num1+num2
because with parameter /A
command set
interprets num1
and num2
automatically as names of variables.
Delayed expansion is nevertheless needed to print the result value stored in variable ans
because command processor expands otherwise %ans%
by nothing respectively the value of previous run on parsing the entire block starting with (
and ending with )
. This can be seen on running your batch file from within a command prompt window with first line changed to @echo on
for debugging.
For more details run in a command prompt window set /?
or help set
and read the output help pages.
start is the name of a command. Therefore it is not good to use this word as name of a label although possible.
By the way: Always use set "variable=value"
and never set variable="value"
as this makes a big difference, see the answers on