Discussion forum for all Windows batch related topics.
Moderator: DosItHelp
-
Adrianvdh
- Posts: 177
- Joined: 16 May 2013 13:00
#1
Post
by Adrianvdh » 09 Jun 2013 13:35
Hello everybody...
I have a small problem when a user enters a string into a "set /p" variable...
Code: Select all
echo Enter Numeric characters only:
echo (1-10 allowed)
set /p num=
if "%num%"GEQ"1" (
if "%num%"LEQ"10" (
echo Correct... 1-10...
pause
))
but that does not work because if a user enters a letter, e.g. "a" then the program will error out.
Is there a way to only enter numbers from 1-10
and it must support spaces in the users entry or the program will close...
!!Incorrect!!
Code: Select all
set /p var=
if %var% == 1 echo fail & pause
!!Correct!!
Code: Select all
set /p var=
if "%var%"=="1" echo Pass & pause
Thank you for your time

-
aGerman
- Expert
- Posts: 4743
- Joined: 22 Jan 2010 18:01
- Location: Germany
#2
Post
by aGerman » 09 Jun 2013 15:11
There are different possibilities. Eg. you could use FINDSTR to figure out whether or not the user entered only numeric input. Here's another way:
Code: Select all
@echo off
setlocal EnableDelayedExpansion
set "num="
set /p "num=Enter a number [1 ... 10]: "
set /a "numeric=num" 2>nul && (
if "!numeric!"=="!num!" (
if !numeric! geq 1 (
if !numeric! leq 10 (
echo correct
) else (
echo input wasn't less than 11
)
) else (
echo input wasn't greater than 0
)
) else (
echo input wasn't numeric
)
) || (
echo failed to assign any numeric value
)
pause
Regards
aGerman
-
foxidrive
- Expert
- Posts: 6031
- Joined: 10 Feb 2012 02:20
#3
Post
by foxidrive » 09 Jun 2013 21:14
This will allow numbers from 1 to 10
EDITED: added quotes to make the input more robust and a line to cater for enter alone being pressed.
Code: Select all
@echo off
:loop
echo Enter Numeric characters only:
echo (1-10 allowed)
set "num="
set /p "num="
if not defined num goto :loop
for /f "delims=1234567890" %%a in ("%num%") do goto :loop
if %num% GTR 10 goto :loop
if %num% LSS 1 goto :loop
echo "%num%"