This question already has an answer here:
Variables are not behaving as expected
(1 answer)
Closed 1 year ago.
I wrote the following batch script, but keep getting a missing operator error
set /a control=1
goto :while
:while
if "!control!"=="1" (
set /p FirstNumber=Please enter your first number:
set /p SecondNumber=Please enter your Second number:
set /a result=%FirstNumber%/%SecondNumber%
echo %FirstNumber% divided by %SecondNumber% = %result%
echo %FirstNumber% divided by %SecondNumber% = %result% >> results.txt
goto :while
)
pause
When I run this code, I keep getting a missing operand error.
This is my output:
Please enter your first number 1: 10
Please enter your second number 1: 2
Missing operand.
divided by =
setlocal enabledelayedexpansion when setting and using a variabled inside a code block:
#echo off
setlocal enabledelayedexpansion
set /a control=1
:while
if !control! equ 1 (
set /p FirstNumber=Please enter your first number:
set /p SecondNumber=Please enter your Second number:
set /a result=FirstNumber / SecondNumber
echo !FirstNumber! divided by !SecondNumber! = !result!
echo !FirstNumber! divided by !SecondNumber! = !result!
goto :while
)
and without needing the parenthesized code block and obviously no need for delayedexpansion
#echo off
set /a control=1
:while
if not %control% equ 1 goto :eof
set /p FirstNumber=Please enter your first number:
set /p SecondNumber=Please enter your Second number:
set /a result=FirstNumber / SecondNumber
echo %FirstNumber% divided by %SecondNumber% = %result%
echo %FirstNumber% divided by %SecondNumber% = %result%
goto :while
Related
The script prompts the user to choose which calculation to perform (call). After I choose an option and calculate the numbers I get random results. Such as 4 + 5 = 27 and 4 * 4 = 0.
#echo off
goto :main
:addition
set /a FNUM1=%~1
set /a FNUM2=%~2
set /a RESULT=FNUM + FNUM2
echo RESULT: %RESULT%
goto :eof
:subtraction
set /a FNUM1=%~1
set /a FNUM2=%~2
set /a RESULT=FNUM - FNUM2
echo RESULT: %RESULT%
goto :eof
:multiplication
set /a FNUM1=%~1
set /a FNUM2=%~2
set /a RESULT=FNUM * FNUM2
echo RESULT: %RESULT%
goto :eof
:division
set /a FNUM1=%~1
set /a FNUM2=%~2
set /a RESULT=FNUM / FNUM2
echo RESULT: %RESULT%
goto :eof
:main
echo Welcome to the calculator
echo Please chose one of the following options:
echo 1 - Addition
echo 2 - Subtraction
echo 3 - Multiplication
echo 4 - Division
echo 5 - Quit
set /p CHOICE=
if "%CHOICE%"=="1" (
echo YOU CHOSE ADDITION!
echo Enter first number:
set /p NUM1=
echo Added by:
set /p NUM2=
call :addition %NUM1% %NUM2%
)
if "%CHOICE%"=="2" (
echo YOU CHOSE SUBTRACTION!
echo Enter first number:
set /p NUM1=
echo Subtracted by:
set /p NUM2=
call :subtraction %NUM1% %NUM2%
)
if "%CHOICE%"=="3" (
echo YOU CHOSE MULTIPLICATION!
echo Enter first number:
set /p NUM1=
echo Multiplied by:
set /p NUM2=
call :multiplication %NUM1% %NUM2%
)
if "%CHOICE%"=="4" (
echo YOU CHOSE DIVISION!
echo Enter first number:
set /p NUM1=
echo Divided by:
set /p NUM2=
call :division %NUM1% %NUM2%
)
if "%CHOICE%"=="5" (
echo Good Bye!
)
goto :eof
I tried to use "/a" for setting FNUM1 and FNUM2, but I still get random results.
Thanks for any advice.
set FNUM1=4
set FNUM2=4
set /a RESULT=%FNUM1%*%FNUM2%
echo RESULT: %RESULT%
RESULT: 16
set /a "RESULT = FNUM1 * FNUM2"
echo RESULT: %RESULT%
RESULT: 16
:main
echo Welcome to the calculator
echo Please chose one of the following options:
echo 1 - Addition
echo 2 - Subtraction
echo 3 - Multiplication
echo 4 - Division
echo 5 - Quit
set "operation="
set "choice="
set /p CHOICE=
if "%CHOICE%"=="1" set "operation=ADDITION"
if "%CHOICE%"=="2" set "operation=SUBTRACTION"
if "%CHOICE%"=="3" set "operation=MULTIPLICATION"
if "%CHOICE%"=="4" set "operation=DIVISION"
if "%CHOICE%"=="5" (
echo Good Bye!
)
if not defined operation echo illegal choice&goto main
echo YOU CHOSE %operation%!
echo Enter first number:
set /p NUM1=
echo Second number:
set /p NUM2=
call :%operation% %NUM1% %NUM2%
goto main
goto :eof
Your primary issue is can be explained by reading some SO items about delayed expansion. In short, within a block (a parenthesised series of lines) any %var% is replaced by the value of var at the time the block is encountered, so changing num? within the block does not alter the values passed to the subroutine - it is num? as it was when the execution of the block began.
Mods: set choice to nothing before executing a set/p because if simply Enter is pushed, the variable will not become empty, but unchanged
establish a new variable, operation and set it to nothing
depending on the choice made (perhaps you should try choice /? from the prompt for a better method) set operation to the appropriate value.
Since each entry produced (nearly) the same text, enter the values, then perform the calculation.
Perhaps you may want to put something like
echo %1 ? %2=%result%
in each subroutine, OR change operation within the subroutine to +, - etc. and in the main routine, after the call :%operation%... (which chooses the subroutine to run) try
echo %num1% %operation% %num2%=%result%
which should fill in operation as set by the routine ":oldvalueofoperation"
I'm a little confused on why in this code, %rem% always comes back as 0 (even when tested with prime numbers). Can someone please help me? Thanks :D
:PRIME
cls
echo What number would you like to check?
set /p num=
set num2=%num%-1
for /l %%i in (2 1 %num2%) do (
set /a rem=%num% %% %%i
)
if %rem% equ 0 goto NOT_PRIME
goto YES_PRIME
:YES_PRIME
echo %num% is a prime number.
goto AGAIN_PRIME
:NOT_PRIME
echo %num% is not a prime number.
goto AGAIN_PRIME
:AGAIN_PRIME
echo Would you like to check another number? (y/n)
set /p ans=
if '%ans%'=='y' goto PRIME
if '%ans%'=='n' goto START
This is only a portion of the code. The problem is that every number that I test, I get "%num% is not a prime number."
There are two problems in this section:
set num2=%num%-1
for /l %%i in (2 1 %num2%) do (
set /a rem=%num% %% %%i
)
if %rem% equ 0 goto NOT_PRIME
First, you need to use set /a to do calculations on a variable, so it should be:
set /a num2=%num%-1
Second, your for loop runs through all your calculations correctly, but your if line ends up checking only the results of the very last calculation. You need to enable delayed expansion and then include the if statement inside the for loop, like this:
for /l %%i in (2 1 %num2%) do (
set /a rem=%num% %% %%i
if !rem! equ 0 goto NOT_PRIME
)
How do I set my if statement to call on different predefined variables based on user input.
Example 1 is red 2 is orange 3 is blue 4 is random.
If user puts 1 they get red. If they put 2 they get orange. If they put 3 they get blue. If they put 4 they get either red, orange, or blue.
The following script shows one way of doing it, using arrays of colors and a method for doing double expansion on a variable (allowing for array access):
#setlocal enableextensions enabledelayedexpansion
#echo off
set color[1]=red
set color[2]=orange
set color[3]=blue
:loop
set /p inp="Enter a number [1=red, 2=orange, 3=blue, 4=random]: "
if "%inp%"=="4" set /a "inp = %RANDOM% %% 3 + 1"
call set color=%%color[%inp%]%%
if "%color%"=="" goto loop
endlocal && set color=%color%
For a more generalised solution, you can look at the following script, which better handles the prompting for arbitrary colors:
#setlocal enableextensions enabledelayedexpansion
#echo off
rem Clear out all color variables then create array.
set color=junk
for /f "delims==" %%a in ('set color') do set %%a=
set /a "count = 0"
set /a "count = count + 1" && set color[!count!]=red
set /a "count = count + 1" && set color[!count!]=orange
set /a "count = count + 1" && set color[!count!]=blue
set /a "count = count + 1" && set color[!count!]=green
set /a "next = count + 1"
rem Loop until color is valid.
:loop
echo.Choices:
for /l %%a in (1,1,%count%) do (
set value=!color[%%a]!
echo. %%a. !value!
)
echo. %next%. Random choice from above
set /p inp="Enter a number: "
rem set inp=1
rem Special handling, choose random value
if "%inp%"=="%next%" set /a "inp = %RANDOM% %% count + 1"
call set color=%%color[%inp%]%%
if "%color%"=="" goto loop
rem Exit local scope, "leaking" color value.
endlocal && set color=%color%
#ECHO Off
SETLOCAL
SET "choices=1=red 2=blue 3=green 4=random"
SET /p inp="[%choices%]: "
FOR /f %%a IN ('echo %choices: =^&echo %') DO SET /a maxchoice=%%a
IF "%inp%"=="%maxchoice%" SET /a inp=%RANDOM% %% (maxchoice - 1) +1
FOR /f "tokens=1,2" %%a IN ('echo %choices: =^&echo %') DO IF "%%a"=="%inp%" SET "hue=%%b"
ECHO %hue%
GOTO :EOF
Here's my version. All you need to do is follow the bouncing ball setting up choices and ensure that random is the last selection.
I started to write a comment as reply to new paxdiablo's solution, but it becomes too large, so I prefer to write my own solution here with all those points included:
#echo off
setlocal EnableDelayedExpansion
rem Create the color array
set n=0
for %%a in (red orange blue green) do (
set /A n+=1
set color[!n!]=%%a
)
set /A next=n+1
rem Show the available colors menu
echo Choices:
echo/
for /L %%i in (1,1,%n%) do echo %%i. !color[%%i]!
echo %next%. Random choice from above
echo/
rem Loop until color is valid
:loop
set /P "inp=Enter a number: "
if "%inp%" equ "%next%" set /A inp=%random% %% n + 1
set color=!color[%inp%]!
if "%color%" equ "" goto loop
echo/
echo Color: %color%
I am translating a shell script to windows batch. What I need to do is take all except 1,2 and last from command line arguments. join them and send to another program as argv.
#echo off
SET subject=%1
set count=%2
set candidates=""
set /a i=0
set /a c=0
FOR %%A IN (%*) DO (
ECHO %%A
set /a i+=1
IF %i% geq 2 (
set /a c+=1;
set candidates[!c!]=%%A
)
)
SET /a count_actual=(%i%-3)
SET /a count_expected=%count%
echo %count_expected%
echo %count_actual%
echo %subject%
echo %candidates%
I want the candidates array be argv[3..n-1]
e.g. If I write batch x 2 a b p it should pass a b to that another program
The problem is loop counter is not being incremented by += operator. If I write echo %1% inside FOR I see 0 always
You should not use for %%A in (%*) as it treats %* as filename set. This may cause problems, especially if you can pass * or ? (wildcard match characters in cmd) in parameters - as they will be expanded to all files satisfying pattern. Second, batch does really know nothing about arrays - a[1] and a[2] are just a shorthand notation for humans - they are two distinct variables.
Given the problem Parse command line, take second parameter as count of parameters to concatenate into a variable, here is my take:
#echo off
setlocal
set subject=%1
shift
set exp_count=%1
if not defined exp_count (
echo Count not specified
exit /b 1
)
set /a "verify=%exp_count%"
if %verify% leq 0 (
echo Count not valid /not a positive integer/
exit /b 2
)
set real_count=0
:loop
shift
if "%~1"=="" goto end_params
set /a real_count+=1
if %real_count% leq %exp_count% set "candidates=%candidates%%~1"
goto loop
)
:end_params
if %real_count% lss %exp_count% (
echo Less parameters passed than specified!
exit /b 3
)
echo %subject%
echo %candidates%
Please note I'm not checking if there is a 'hanging' parameter (the last, not being concatenated) but it should be trivial to add that check. I left it out on purpose to make the code more flexible.
I have two answers for your question:
1- The first problem is that in IF %i% ... command the value of i variable not change (although set /a i+=1 command will correctly increment the variable) and the way to solve it is by including setlocal EnableDelayedExpansion command at beginning and enclose i in percents signs this way: IF !i! ... (as said in previous answers). However, you must note that an array variable in Batch is different than a simple variable with same name (they both can exist at same time), so array elements must always be written with subscripts and there is NO way to process an entire array in a single operation. See this topic for further details.
In your program you must transfer the elements of candidates array into a simple variable, that in the example below have the same name (just to state my point):
#echo off
setlocal EnableDelayedExpansion
SET subject=%1
set count=%2
set candidates=""
set /a i=0
set /a c=0
FOR %%A IN (%*) DO (
ECHO %%A
set /a i+=1
IF !i! geq 2 (
set /a c+=1
set candidates[!c!]=%%A
)
)
SET /a count_actual=(%i%-3)
SET /a count_expected=%count%
echo %count_expected%
echo %count_actual%
echo %subject%
REM Transfer "candidates" array elements into "candidates" simple variable:
set candidates=
FOR /L %%i IN (1,1,%c%) do (
set candidates=!candidates! !candidates[%%i]!
)
REM Show "candidates" simple variable:
echo %candidates%
Note that in Batch files you may insert commas, semicolons and equal-signs as separators instead spaces in most commands. However, SET /A command have other rules at this respect, so the semicolon must be omitted.
2- Independently of the array management explained above, this is the way I would solve your problem using a list instead of an array:
#echo off
SET subject=%1
shift
set count=%1
set candidates=
set lastArg=
set i=0
:nextArg
shift
if "%1" equ "" goto endArgv
set /a i+=1
set candidates=!candidates! !lastArg!
set lastArg=%1
goto nextArg
:endArgv
SET /a count_actual=i-3, count_expected=count
echo %count_expected%
echo %count_actual%
echo %subject%
echo %candidates%
Antonio
Yes your code will not increment i. Batch variable replacement occurs when a block is parsed, not when it is executed. The entire for block is parsed once, so %i% is replaced with zero before the for block is executed.
To disable that you need to enable delayed expansion and change your variable escape characters from %'s to !'s to have the replacement made at runtime. Then you will see i incremented in the for loop.
#echo off
Setlocal EnableDelayedExpansion
SET subject=%1
set count=%2
set candidates=""
set /a i=0
set /a c=0
FOR %%A IN (%*) DO (
ECHO %%A
set /a i+=1
IF !i! geq 2 (
set /a c+=1
set candidates[!c!]=%%A
)
)
SET /a count_actual=(%i%-3)
SET /a count_expected=%count%
echo %count_expected%
echo %count_actual%
echo %subject%
echo %candidates%
You will also need to get rid of the ; at the end of the set /a c+=1; line and I'm not sure what you are trying to do on line set candidates[!c!]=%%A as the brackets don't mean anything in batch.
While there are a bunch of answers already listed, I decided to add one more. My approach is to keep the answer as simple as possible for your specific needs. If you have any questions feel free to ask.
This will create the array as you desired [3,...,n-1] without the need for delayed expansion or fancy logic.
#echo off
:: Get the First Two Parameters
set "subject=%1"
shift
set "count=%1"
shift
:: Loop through the rest
set "index=0"
:NextParam
set "param=%1"
shift
set "next=%1"
:: Skip the last parameter
if not defined next goto EndParam
set "candidates[%index%]=%param%"
set /a "index+=1"
goto NextParam
:EndParam
set "count_actual=%index%"
set "count_expected=%count%"
:: Show the Results
echo %count_actual%
echo %count_expected%
echo %subject%
set candidates
Here is an alternate where the candidates are stored in a space delimited string instead of seperate variables. Replace the space between the %candidates% %param% to whatever delimiter you desire.
#echo off
:: Get the First Two Parameters
set "subject=%1"
shift
set "count=%1"
shift
:: Loop through the rest
set "index=0"
:NextParam
set "param=%1"
shift
set "next=%1"
:: Skip the last parameter
if not defined next goto EndParam
set "candidates=%candidates% %param%"
set /a "index+=1"
goto NextParam
:EndParam
set "count_actual=%index%"
set "count_expected=%count%"
:: Show Results
echo %count_actual%
echo %count_expected%
echo %subject%
echo %candidates%
I'm experimenting with a Windows batch file to perform a simple operation which requires the user to enter a non-negative integer. I'm using simple batch-file techniques to get user input:
#ECHO OFF
SET /P UserInput=Please Enter a Number:
The user can enter any text they want here, so I would like to add some routine to make sure what the user entered was a valid number. That is... they entered at least one character, and every character is a number from 0 to 9. I'd like something I can feed the UserInput into. At the end of the routine would be like an if/then that would run different statements based on whether or not it was actually a valid number.
I've experimented with loops and substrings and such, but my knowledge and understanding is still slim... so any help would be appreciated.
I could build an executable, and I know there are nicer ways to do things than batch files, but at least for this task I'm trying to keep it simple by using a batch file.
You're probably not doing this in a DOS batch file. Or at least, support for set /p is unheard of for me in DOS :-)
You could use substrings. In fact I have written a parser for a specific regular language that way once, but it's cumbersome. The easiest way would probably be to assign the contents of %userinput% to another variable, using set /a. If the result comes out as 0 you need to check whether the input itself was 0, otherwise you can conclude it was a non-number:
#echo off
setlocal enableextensions enabledelayedexpansion
set /p UserInput=Enter a number:
set /a Test=UserInput
if !Test! EQU 0 (
if !UserInput! EQU 0 (
echo Number
) else (
echo Not a number
)
) else (
echo Number
)
However, this works only for numbers in the range of Int32. If you just care for any number (possibly floating-point as well) then you need to resort to the loop-based approach of dissecting it.
NOTE: Updated to solve the space issues. However, there is still a problem lurking: Entering 123/5 yields "number", since set /a can evaluate this ...
Thanks all. I was trying to make it harder for myself looking at loops and string manipulation. I used your tips on math evaluation and comparison. Here's what I finally came up with as my concept script:
:Top
#ECHO OFF
ECHO.
ECHO ---------------------------------------
SET /P UserInput=Please Enter a Number:
ECHO.
ECHO UserInput = %UserInput%
ECHO.
SET /A Evaluated=UserInput
ECHO Math-Evaluated UserInput = %Evaluated%
if %Evaluated% EQU %UserInput% (
ECHO Integer
IF %UserInput% GTR 0 ( ECHO Positive )
IF %UserInput% LSS 0 ( ECHO Negative )
IF %UserInput% EQU 0 ( ECHO Zero )
REM - Other Comparison operators for numbers
REM - LEQ - Less Than or Equal To
REM - GEQ - Greater Than or Equal To
REM - NEQ - Not Equal To
) ELSE (
REM - Non-numbers and decimal numbers get kicked out here
ECHO Non-Integer
)
GOTO Top
This method catches all numbers and can detect whether it's positive, negative, or zero. Any decimal or string will be detected as non-integers. The only edge case I've found is a string with spaces. For example, the text "Number 1" will cause the script to crash/close when the user input is evaluated as math. But in my situation, this is fine. I don't want my script to go on with invalid input.
You can also use a quite simple trick:
echo %userinput%|findstr /r /c:"^[0-9][0-9]*$" >nul
if errorlevel 1 (echo not a number) else (echo number)
This uses findstr's regular expression matching capabilities. They aren't very impressive but useful at times.
This is the same idea as that of Johannes..
SET /A sets a numeric value. If the input is not a number, it changes it to 0.
That's what you can exploit here to do your check.
#ECHO OFF
SET /P UserInput=Please Enter a Number:
IF %UserInput% EQU 0 GOTO E_INVALIDINPUT
SET /A UserInputVal="%UserInput%"*1
IF %UserInputVal% GTR 0 ECHO UserInput "%UserInputVal%" is a number
IF %UserInputVal% EQU 0 ECHO UserInput "%UserInputVal%" is not a number
GOTO EOF
:E_INVALIDINPUT
ECHO Invalid user input
:EOF
As an alternative, you could always create a little javascript file and call it from your batchfile. With parseInt() you could force the input to be an integer, or you could roll your own function to test the input.
Writing the javascript is just as fast as the batchfile, but it's much more powerful. No IDE or compiler required; notepad will do. Runs on every windows box, just like your batchfiles. So why not make use of it?
You can even mix batchfiles and javascript. Example:
contents of sleep.js:
var SleepSecs=WScript.Arguments.Item(0);
WScript.Sleep(SleepSecs*1000)
contents of sleep.cmd:
cscript /nologo sleep.js %1
You can now call this from a batchfile to make your script sleep for 10 seconds. Something like that is difficult to do with just a plain batchfile.
sleep 10
As pointed out by ghostdog74, the answers posted by Joey Mar 26 '09 (score 10) and Wouter van Nifterick Mar 26 '09 (score 5) don't work.
The answer posted by Joey Mar 25 '10 (score 2) does work, except that redirection symbols and '&' cause syntax errors.
I think the best and simplest solution is the one posted by Sager Oct 8 '14 (score 0). Unfortunately, it has a typo: ‘"%a"’ should be ‘"%a%"’.
Here's a batch file based on Sager's answer. Redirection symbols and '&' in the input don't cause problems. The only problems I could find were caused by strings containing double quotes.
#echo off & setlocal enableextensions & echo.
set /p input=Enter a string:
SET "x=" & for /f "delims=0123456789" %%i in ("%input%") do set x=%%i
if defined x (echo Non-numeral: "%x:~0,1%") else (echo No non-numerals)
In addition to the remark about the error that occures when spaces are part of the users input. You can use errorlevel errorlevel=9165. It can be used for the spaces in a string or for the error handling of 'no' input.
Kind Regards,
Egbert
You might also like this one - it's short and easy. This one use the multiplication trick to set TestVal. Comparing TestVal against UserInput allows all numeric values to get through including zeroes, only non-numerics will trigger the else statement. You could aslo set ErrorLevel or other variables to indicate a failed entry
#ECHO OFF
SET TestVal=0
SET /P UserInput=Please Enter a Number:
SET /A TestVal="%UserInput%"*1
If %TestVal%==%UserInput% (
ECHO You entered the number %TestVal%
) else ECHO UserInput "%UserInput%" is not a number
GOTO EOF
:EOF
I know this is years old, but just to share my solution.
set /p inp=Int Only :
:: Check for multiple zeros eg : 00000 ::
set ch2=%inp%-0
if %inp% EQU 0 goto :pass
if [%inp%]==[] echo Missing value && goto :eof
if %inp:~0,1%==- echo No negative integers! && goto :eof
set /a chk=%inp%-10>nul
if %chk%==-10 echo Integers only! && goto :eof
:pass
echo You shall pass
:eof
Tested and working on Windows 8.
you can reinvent the wheel and grow a few white hairs doing string validation in batch, or you can use vbscript
strInput = WScript.Arguments.Item(0)
If IsNumeric(strInput) Then
WScript.Echo "1"
Else
WScript.Echo "0"
End If
save it as checkdigit.vbs and in your batch
#echo off
for /F %%A in ('cscript //nologo checkdigit.vbs 100') do (
echo %%A
rem use if to check whether its 1 or 0 and carry on from here
)
You can validate any variable if its number:
SET "var="&for /f "delims=0123456789" %i in ("%a") do set var=%i
if defined var (echo."NIC">nul) else (echo."number")
If you want some sort of a loop and default set up for that particular question, then here's my method for doing this.
Notes on the code within.
#echo off
setlocal EnableDelayedExpansion
set "ans1_Def=2"
:Q1
set /p "ans1=Opt 1 of 1 [Value 1-5 / Default !ans1_Def!]: "
:: If not defined section. This will use the default once the ENTER key has been
:: pressed and then go to :Q2.
if not defined ans1 (
echo/ & echo ENTER hit and the default used. Default is still: !ans1_Def! & echo/
set "ans1=!ans1_Def!" && goto :Q2 )
:: This section will check the validity of the answer. The "^[1-5]$" will work
:: for only numbers between one and five in this example but this can be changed
:: to pretty much suit the majority of cases. This section will also undefine
:: the ans1 variable again so that hitting the ENTER key at the question
:: will work.
echo %ans1%|findstr /r /c:"^[1-5]$" >nul
if errorlevel 1 (
echo/ & echo At errorlevel 1. Wrong format used. Default is still: !ans1_Def! & echo/
set "ans1=" && goto Q1
) else ( echo Correct format has been used. %ans1% is the one. && goto :Q2 )
:Q2
echo/
echo -----------------------------
echo/
echo Now at the next question
echo !ans1!
echo/
pause
exit
Try this:
set /p numeric=enter a number
(
(if errorlevel %numeric% break ) 2>nul
)&&(
echo %numeric% is numeric
)||(
echo %numeric% is NOT numeric
)
Just try this
#echo off
SET constNum=100
:LOOP
Set /p input=Please input a number less than %constNum% :
if "%input%" == "" echo Blank is not allowed & goto LOOP
SET "notNumChar="
for /f "delims=0123456789" %%i in ("%input%") do set notNumChar=%%i
if defined notNumChar (
echo %input% is a string
goto LOOP
) else (
REM Remove leading 0 if it has. eg: 08→8
FOR /F "tokens=* delims=0" %%A IN ("%input%") DO SET inputNum=%%A
)
REM Compare
if defined inputNum (
echo %inputNum%
if %inputNum% equ %constNum% & goto LOOP
if %inputNum% gtr %constNum% & goto LOOP
if %inputNum% lss %constNum% & goto CONTINUE
)
:CONTINUE
:: Your code here
:ASK
SET /P number= Choose a number [1 or 2]:
IF %number% EQU 1 GOTO ONE
IF %number% NEQ 1 (
IF %number% EQU 2 GOTO TWO
IF %number% NEQ 2 (
CLS
ECHO You need to choose a NUMBER: 1 OR 2.
ECHO.
GOTO ASK
)
)
It works fine to me. If he chooses numbers less or greater, strings, floating number etc, he wil receive a message ("You need to choose a NUMBER: 1 OR 2.") and the INPUT will be asked again.
#echo off
setlocal enableextensions enabledelayedexpansion
set /p UserInput=Enter a number:
set /a Test=UserInput
if !Test! EQU 0 (
if !UserInput! EQU 0 (
echo Number
) else (
echo Not a number
)
) else (
echo Number
)
yeaph everthing is great
but you forget about one little thing
0 also is a digit
;(
This is more of a user friendly way.
if %userinput%==0 (
cls
goto (put place here)
)
if %userinput%==1 (
cls
goto (put place here)
)
if %userinput%==2 (
cls
goto (put place here)
)
if %userinput%==3 (
cls
goto (put place here)
)
if %userinput%==4 (
cls
goto (put place here)
)
if %userinput%==5 (
cls
goto (put place here)
)if %userinput%==6 (
cls
goto (put place here)
)if %userinput%==7 (
cls
goto (put place here)
)
if %userinput%==8 (
cls
goto (put place here)
)
if %userinput%==9 (
cls
goto (put place here)
)
This can be used for any type of user input.
for me this is working for all non-zero values ..should i be cautious of some rare cases?
set /a var = %1
if %var% neq 0 echo "it is number"
pause