Confusion on "for /l in %%i ..." always renders "0" - windows

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
)

Related

Batch missing operand errpr [duplicate]

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

String validation with multiple levels required using CMD command

I have three requirements I need to meet when validating a password. I have figure out with the help of others how to verify that the password is at least seven characters long and the user name is not part of the password.
My last requirement is to check to see if a string contains characters from three of the following four groups:
English uppercase characters (A through Z)
English lowercase characters (a through z)
Base 10 digits (0 through 9)
Non-alphabetic characters (for example, !, $, #, %)
For example (Hou$e or House1) would pass but (House, house or hou$e) would fail
The call to ":checkRequirement3" is where I would like to make this finial check. The password is valid if all three requirements are meet.
#echo off
setlocal
set /p userName=Username:
set /p userPassword=Password:
call :strlen result userPassword
call :checkRequirement1
call :checkRequirement2
call :checkRequirement3
ECHO Finished
Pause
:strlen <resultVar> <stringVar>
REM THIS DETERMINES THE LENGTH OF THE PASSWORD
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
:checkRequirement1
REM THIS CHECKS IF PASSWORD IS AT LEAST 7 CHARACTERS LONG
(
if %result% GEQ 7 (
exit /b
)else (
GOTO passwordFail
)
:checkRequirement2
REM THIS CHECKS IF THE USER NAME IS INCLUDED IN THE PASSWORD
setlocal enabledelayedexpansion
set replacedUsername=!userPassword:%userName%=!
if not !replacedUsername!==%userPassword% (
GOTO passwordFail
)else (
exit /b
)
:checkRequirement3
REM THIS CHECKS IF THE PASSWORD CONTAINS CHARACTERS FROM 3 OF THE FOLLOWING GROUPS
REM English uppercase characters (A through Z)
REM English lowercase characters (a through z)
REM Base 10 digits (0 through 9)
REM Non-alphabetic characters (for example, !, $, #, %)
ECHO This Requirement not finished
Pause
exit /b
:passwordFail
ECHO Password Failed Requirement
PAUSE
exit /b
)
#ECHO OFF
SETLOCAL
FOR %%t IN (Hou$e House1 House, house hou$e hou%%%%se hou^^se) DO CALL :test "%%t"
GOTO :EOF
:test
SET /a count=0
>"q43120516.txt" ECHO %~1
TYPE "q43120516.txt"
FOR %%s IN ("[ABCDEFGHIJKLMNOPQRSTUVWXYZ]"
"[abcdefghijklmnopqrstuvwxyz]"
"[!##&$%%^]"
"[0123456789]") DO FINDSTR /r %%s "q43120516.txt">nul&IF NOT ERRORLEVEL 1 SET /a count+=1
ECHO found %count% groups IN %~1
DEL "q43120516.txt"
GOTO :EOF
naturally, the name of the temporary file "q43120516.txt" is irrelevant.
A few little things to note here:
Certain characters, like % and ^ which have a special meaning to cmd need to be doubled - sometimes quadrupled.
Yes, I'm aware that in theory you could use echo %~1|. Try it.
Yes, I'm aware that in theory you could use [A-Z]. Try it.
This will correctly verify that the password is using 3 out of the 4 groups.
setlocal enabledelayedexpansion
SET /P userPassword=UserPassword:
SET /P userPassword=UserPassword=%userPassword:&=^&%
SET /a count=0
echo %userPassword:&=^&% | findstr /R /C:"[ABCDEFGHIJKLMNOPQRSTUVWXYZ]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[abcdefghijklmnopqrstuvwxyz]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[!##&$%%^]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[0123456789]">null&if not errorlevel 1 SET /a count+=1
If %count% GEQ 3 (
echo Password Meets requirement
exit /b
) else (
goto passwordFail
)

optimization of a windows batch file arcade game

I made a batch file game, and it works, but it is choppy and ugly. I already know about threading, but I don't want to implement that in my first version. I am hoping to have the optimization down before I start doing more advanced things with this game. my question is this: What optimizations can I make to this game, so that it will 1. not be choppy and 2. not be quite so annoying in the display. any ideas or comments about how to make it faster clearer or take less memory are welcome, however, please do not post answers like: "don't use batch" "rewrite it in (insert language here)" "do this part with vb-script" etc... as they are not helpful, nor do they answer the question. any and all non batch hating criticism is welcomed.
here is the code:
#setlocal enableextensions enabledelayedexpansion
#echo off
color 0a
mode con lines=35 cols=50
cls
set instructions=use a and d to move left and right, w to fire. use q to quit and p to pause.
set height=30
set length=
set screen=50
set swidth=20
set amo=8
set lives=3
set 1=0
set 2=1
set 3=2
set 4=3
set 5=4
set 6=0
set 7=1
set 8=2
set 9=3
set 10=4
echo. What quality would you like?
echo. 1. fast, but the graphics suck!
echo. 2. medium both ways.
echo. 3. slow, but the graphics are better!
choice /n /c:123
set firequal=%errorlevel%00
cls
echo %instructions%
echo.
pause
cls
::main
:controls
cls
if %height% EQU 2 goto gameover
if %lives% LSS 1 goto gameover
cls
set /a shouldbomb+=1
set /a whenbomb=shouldbomb%%15
if %whenbomb% == 9 call :bomb
if '%ret%'=='1' exit /b
set ret=
cls
set alive=
for /l %%i in (1,1,10) do if defined %%i set alive=true
if not defined alive goto win
cls
for /l %%i in (1,1,5) do (
if defined %%i (
set /p a=[_] <nul
) else (
set /p a=... <nul
)
)
echo.
for /l %%i in (6,1,10) do (
if defined %%i (
set /p a=[_] <nul
) else (
set /p a=... <nul
)
)
for /l %%a in (1,1,%height%) do echo.
echo %length%[]
echo.
for /l %%i in (1,1,%amo%) do set /p a=^|<nul
echo.
choice /c adwqp0 /n /t 1 /d 0
if %errorlevel% equ 1 goto :left
if %errorlevel% equ 2 goto :right
if %errorlevel% equ 3 goto :fire
if %errorlevel% equ 4 (cls&exit /b)
if %errorlevel% equ 5 pause&goto controls
if %errorlevel% equ 6 goto :inactive
goto controls
::move player left
:left
if '!length!' NEQ '' set length=!length:~0,-1!
goto controls
::move player right
:right
call :strlen shiplen length
if %shiplen% GTR %swidth% goto controls
set length=%length%
goto controls
::fire a shot upwards
:fire
if '!amo!' LSS '1' goto controls
cls
set /a amo-=1
for /l %%i in (%height%,-1,2) do (
cls
for /l %%i in (1,1,5) do (
if defined %%i (
set /p a=[_] <nul
) else (
set /p a=... <nul
)
)
echo.
for /l %%i in (6,1,10) do (
if defined %%i (
set /p a=[_] <nul
) else (
set /p a=... <nul
)
)
for /l %%j in (1,1,%%i) do echo.
echo %length% ^
set /a ship=height-%%i-1
for /l %%b in (1,1,!ship!) do echo.
echo %length%[]
echo.
for /l %%i in (1,1,%amo%) do set /p a=^|<nul
echo.
for /l %%a in (1,1,%firequal%) do call >nul 2>&1
)
call :checkshot
set /a shouldbomb+=1
set /a whenbomb=shouldbomb%%2
if %whenbomb% == 0 call :bomb
goto controls
:inactive
if %amo% LSS 10 set /a amo+=1
if !height! NEQ 2 set /a height-=1
call :bomb
goto controls
:bomb
:btop
set bombx=
for /l %%a in (1,1,10) do (
if defined %%a (
set /a randomnum=%random%%%5
if '!%%a!'=='%randomnum%' (
set /a "bombx=5*(!%%a!)"
)
)
)
)
if not defined bombx goto btop
cls
set bomb=
for /l %%b in (1,1,!bombx!) do (
set bomb=!bomb!
)
set /a bombh=height-1
for /l %%c in (1,1,!bombh!) do (
cls
for /l %%i in (1,1,5) do (
if defined %%i (
set /p a=[_] <nul
) else (
set /p a=... <nul
)
)
echo.
for /l %%i in (6,1,10) do (
if defined %%i (
set /p a=[_] <nul
) else (
set /p a=... <nul
)
)
for /l %%b in (1,1,%%c) do echo.
echo !bomb!x
set /a ship=height-%%c-1
for /l %%b in (1,1,!ship!) do echo.
echo %length%[]
echo.
for /l %%i in (1,1,%amo%) do set /p a=^|<nul
echo.
for /l %%a in (1,1,%firequal%) do call >nul 2>&1
)
if "%bomb%" == "%length%" call :looselife
if "%bomb% " == "%length%" call :looselife
if "%bomb%" == "%length% " call :looselife
if "%bomb% " == "%length%" call :looselife
if "%bomb%" == "%length% " call :looselife
exit /b
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
:checkshot
call :strlen slen length
for /l %%i in (0,5,20) do (
if '!slen!' == '%%i' (
set /a hit=%%i
set /a hit=hit/5+1
set /a hit2=hit+5
if not defined !hit2! set !hit!=
if defined !hit2! set !hit2!=
)
)
exit /b
:looselife
set /a lives-=1
set length=
set 1=0
set 2=1
set 3=2
set 4=3
set 5=4
if %lives% GTR 1 timeout /nobreak 1 >nul 2>&1
exit /b
:win
cls
echo YOU WIN^!^!^!^!
echo.
echo GOOD JOB^!^!^!
echo.
pause
cls
exit /b
:gameover
cls
echo YOU LOOSE.
echo.
echo PLEASE TRY AGAIN.
echo.
pause
cls
set ret=1
thank you in advance for any help.
P.S. I am writing this game to convince a friend to learn something besides html, and while batch isn't the best, he uses windows, and he will only do something simple for now. He is twelve, so I think batch is best option.
You can definitely improve things considerably. I know, because I have already produced a very smooth and playable version of SNAKE using pure Windows batch! Give it a try - I think you will be surprised and impressed with what musty old batch can do :-)
Of course the link has the code, but it also has pointers on some of the techniques I used to make the came perform so well. Read the entire first post carefully, and read the remainder of the thread for some additional important developments.
Optimization is a large topic. Rather than repeat all the information here, I will simply summarize. Follow the link for more details.
1) Minimize GOTO and CALL statements.
For major speed improvements over traditional batch function calls, we developed batch macros with arguments at DosTips. That first macro link develops a number of important concepts. However, the macro form I actually used in the game uses a more elegant solution with arguments appended.
A GOTO loop can be replaced by an infinite FOR loop that runs in a new process. You break out of the loop by EXITing the child process.
2) Greatly improve key press detection in a non-blocking way.
A major limitation of batch is the inability to easily detect a keypress without blocking progress of the game. The problem can be solved by using two processes, both running in the same console window. The controller process reads keypresses and sends them to the main game process via a text file. The controller has multiple modes of operation. The game process sends commands to the controller via another text file. This technique requires careful coordination of input and output redirection.
The CHOICE command is not available on XP. Some folks at DosTips discovered how to use XCOPY to simulate most of the features of CHOICE, and it works on all versions of Windows. Very cool!
3) Screen painting
Building the screen character by character is extremely slow. It is much faster to build the initial screen once, using an "array" of strings with fixed length. Each character within a string represents one "pixel". The position within a string represents the X coordinate, and the string row number represents the Y coordinate. Generally, only a few pixels change for any given screen refresh. Pixels can be "plotted" by using SET with simple substring operations. The entire screen can then be quickly refreshed using CLS followed by ECHO of each line in the screen array.
4) Smooth animation
The amount of work required to perform game logic and screen plotting can vary significantly depending on the current game context. But you want the animation to be smooth. Rather than have a fixed delay between each round of movement, you can instead measure the time since the screen was last updated. Only continue when a pre-determined amount of time has elapsed. As long as all game logic and plotting can occur within the delay time period, then the animation will always be smooth.
Here is pseudo code that describes the timing logic:
initialize delayTime
initialize previousTime
loop (
get currentTime
set diffTime = currentTime - previousTime
if diffTime >= delayTime (
set previousTime = currentTime
perform user input, game logic, and screen refresh
)
)
And here is actual code that computes the elapsed time since last movement. The currentTime (t2) is measured as centiseconds (1/100 second) since midnight. It is parsed and computed using FOR /F and basic math. The diffTime (tDiff) will be negative if the previousTime (t1) is before midnight and the currentTime (t2) is after midnight. If negative, then 1 day is added to diffTime to get the correct time interval.
%=== compute time since last move ===%
for /f "tokens=1-4 delims=:.," %%a in ("!time: =0!") do set /a "t2=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100, tDiff=t2-t1"
if !tDiff! lss 0 set /a tDiff+=24*60*60*100
There is so much more that can be discussed. Try the SNAKE.BAT game, study the post and the code, and see where your imagination can take you.
Some optimizations
1) It's better to use good variable names.
Names like 1, 2 ... 10 are really bad, nobody knows what they are good for, even you self will not remember in a month.
And then it's also a bad idea as it can have many side effects to use variables begining with digits, in batch there are many where these will simply fail.
2) You should combine your output to complete lines before outputting it.
Then you don't need set/p only echo and it's faster.
3) calls to functions like :strlen should be avoided, calls at all are expensive and in your case it should be possible to solve the same without strlen at all.
4) The function :checkshot don't need a for loop.
I don't understand what you try to do there, but you test slen if it is a muliple of 5.
This could be solved with
set /a remainder=slen %% 5
if !remainder! EQU 0 (
...
5) Follow the tips of dbenham :-)

LastIndexOf in Windows batch

I need to implement a function in a Windows batch script to get the LastIndexOf a character into a given string.
For example: Given the following string, I need to get the last index of character '/':
/name1/name2/name3
^
So I need to get the value:
12
Joey's solution works, but the character to find is hard coded, and it is relatively slow.
Here is a parametized function that is fast and can find any character (except nul) within the string. I pass the name of variables containing the string and the character instead of string literals so that the function easily supports all characters.
#echo off
setlocal
set "test=/name1/name2/name3"
set "char=/"
::1st test simply prints the result
call :lastIndexOf test char
::2nd test stores the result in a variable
call :lastIndexOf test char rtn
echo rtn=%rtn%
exit /b
:lastIndexOf strVar charVar [rtnVar]
setlocal enableDelayedExpansion
:: Get the string values
set "lastIndexOf.char=!%~2!"
set "str=!%~1!"
set "chr=!lastIndexOf.char:~0,1!"
:: Determine the length of str - adapted from function found at:
:: http://www.dostips.com/DtCodeCmdLib.php#Function.strLen
set "str2=.!str!"
set "len=0"
for /L %%A in (12,-1,0) do (
set /a "len|=1<<%%A"
for %%B in (!len!) do if "!str2:~%%B,1!"=="" set /a "len&=~1<<%%A"
)
:: Find the last occurrance of chr in str
for /l %%N in (%len% -1 0) do if "!str:~%%N,1!" equ "!chr!" (
set rtn=%%N
goto :break
)
set rtn=-1
:break - Return the result if 3rd arg specified, else print the result
( endlocal
if "%~3" neq "" (set %~3=%rtn%) else echo %rtn%
)
exit /b
It wouldn't take much modification to create a more generic :indexOf function that takes an additional argument specifying which occurance to find. A negative number could specify to search in reverse. So 1 could be the 1st, 2 the 2nd, -1 the last, -2 penultimate, etc.
(Note: I'm assuming Windows batch files because, frankly, I have only seen a single question asking for an actual DOS batch file here so far. Most people simply misattribute “DOS” to anything that has a window of gray-on-black monospaced text without knowing what they're actually talking of.)
Just loop through it, updating the index as you go:
#echo off
setlocal enabledelayedexpansion
set S=/name1/name2/name3
set I=0
set L=-1
:l
if "!S:~%I%,1!"=="" goto ld
if "!S:~%I%,1!"=="/" set L=%I%
set /a I+=1
goto l
:ld
echo %L%
I know this question is a bit old now, but I needed a function that could find the location of a substring (of any length) within a string, and adapted dbenham's solution for my purposes. This function also works with individual characters within a string, as asked for in the original question, and can search for specific instances (as suggested by dbenham).
To use this function, the actual strings must be passed. Dbenham does note that this supports fewer characters than passing the actual variables, but I find that this variant is more reuseable (especially with pipes).
The third argument takes the instance that should be found, with negative numbers specifying to search from the end. The index returned is the offset from the start of the string to the first character in the substring.
#ECHO off
SET search_string=sub
CALL :strIndex "The testing subjects subjects to testing." "%search_string%" -2
ECHO %ERRORLEVEL%
PAUSE
EXIT
:strIndex string substring [instance]
REM Using adaptation of strLen function found at http://www.dostips.com/DtCodeCmdLib.php#Function.strLen
SETLOCAL ENABLEDELAYEDEXPANSION
SETLOCAL ENABLEEXTENSIONS
IF "%~2" EQU "" SET Index=-1 & GOTO strIndex_end
IF "%~3" EQU "" (SET Instance=1) ELSE (SET Instance=%~3)
SET Index=-1
SET String=%~1
SET "str=A%~1"
SET "String_Length=0"
FOR /L %%A IN (12,-1,0) DO (
SET /a "String_Length|=1<<%%A"
FOR %%B IN (!String_Length!) DO IF "!str:~%%B,1!"=="" SET /a "String_Length&=~1<<%%A"
)
SET "sub=A%~2"
SET "Substring_Length=0"
FOR /L %%A IN (12,-1,0) DO (
SET /a "Substring_Length|=1<<%%A"
FOR %%B IN (!Substring_Length!) DO IF "!sub:~%%B,1!"=="" SET /a "Substring_Length&=~1<<%%A"
)
IF %Substring_Length% GTR %String_Length% GOTO strIndex_end
SET /A Searches=%String_Length%-%Substring_Length%
IF %Instance% GTR 0 (
FOR /L %%n IN (0,1,%Searches%) DO (
CALL SET StringSegment=%%String:~%%n,!Substring_Length!%%
IF "%~2" EQU "!StringSegment!" SET /A Instance-=1
IF !Instance! EQU 0 SET Index=%%n & GOTO strIndex_end
)) ELSE (
FOR /L %%n IN (%Searches%,-1,0) DO (
CALL SET StringSegment=%%String:~%%n,!Substring_Length!%%
IF "%~2" EQU "!StringSegment!" SET /A Instance+=1
IF !Instance! EQU 0 SET Index=%%n & GOTO strIndex_end
))
:strIndex_end
EXIT /B %Index%

Batch File input validation - Make sure user entered an integer

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

Resources