allow a space in user input without quotes
Moderator: DosItHelp
allow a space in user input without quotes
Hi I have a batch file that contains a list of possible words the user can type in and the file will "echo" a different word but the user must type in one or two words and the first word will always be "to"if there are two words for example to run or the use could input a single word Like jump. Thanks sorry for any typos auto correct is correcting things that it shouldn't
Re: allow a space in user input without quotes
OK I have a batch file named file.bat
Is there a way to allow the user to enter to jump without adding quotes ?
Code: Select all
@echo off
Cls
Set /p action
If %action%== jump echo jump
If %action%== to jump echo jumping
Is there a way to allow the user to enter to jump without adding quotes ?
-
- Expert
- Posts: 1166
- Joined: 06 Sep 2013 21:28
- Location: Virginia, United States
Re: allow a space in user input without quotes
Just put quotes around the check.
Code: Select all
@echo off
Cls
Set /p action=
If "%action%"=="jump" echo jump
If "%action%"=="to jump" echo jumping
pause
Re: allow a space in user input without quotes
Without adding quotes:
penpen
Code: Select all
@echo off
Cls
Set /p "action="
If %action: =^ % == jump echo jump
If %action: =^ % == to^ jump echo jumping
penpen
Re: allow a space in user input without quotes
penpen wrote:Without adding quotes:Code: Select all
@echo off
Cls
Set /p "action="
If %action: =^ % == jump echo jump
If %action: =^ % == to^ jump echo jumping
penpen
I hope the SO police don't see that code!
Re: allow a space in user input without quotes
In such a case i would have edited my post and explained the code - i don't want to mess with the official SO police (i am misusing the quote-block for that):
penpen
penpen wrote:You only must escape the space characters with a '^' (tilde) in order to make it work within the expression of the "if-statement".
Here is a simple example that demonstrates the use of this special character and solves the task (just remove the last line):Code: Select all
@echo off
Cls
Set /p "action="
If %action: =^ % == jump call ^
:jumping "1"
If %action: =^ % == to^
jump ^
echo^
:jumping
if "%~1" == "1" echo jump & goto ^
:eof
echo I get up, and nothing gets me down.
penpen
Re: allow a space in user input without quotes
Or use FOR /F to make the code generic:
Dave Benham
Code: Select all
@echo off
setlocal
cls
set /p "action="
for /f "tokens=1,2" %%A in ("%action%") do (
if "%%B" equ "" (echo(%%A) else if /i "%%A" equ "to" (echo %%Bing) else echo ERROR
)
Dave Benham