0

If I use the if command but enter a value that isn't an option it goes to a random section, for example:

set /p test

if %test% == x goto home

if %test% == y goto home2

:home
echo hi
pause

:home2
echo how are you
pause

:pie
echo want some pie?

if I enter x, it goes to home but if I enter c or w it goes to pie or home2, how do I fix that?

  • If the first two if don't trigger program flow leads directly to :home, so what? Also after the pause it continues with all other labels. There is an equal sign missing in the `set /p test=` The last assertion with c and w is nonsense. –  Apr 27 '17 at 16:49
  • @1337Nico Use the command [choice](https://ss64.com/nt/choice.html) if the only acceptable inputs are `x` or `y` which is much better than using `set /P` were the user as the freedom to enter nothing, `x` or `y` or `"let batch file exit with syntax error or do weird things >!<`. – Mofi Apr 27 '17 at 17:29
  • Possible duplicate of [Why is string comparison after prompting user for a string/option not working as expected?](http://stackoverflow.com/questions/41434001/why-is-string-comparison-after-prompting-user-for-a-string-option-not-working-as) – Mofi Apr 27 '17 at 17:29
  • @1337Nico - If you find my answer helpful, please consider to click the checkmark next to my answer to accept it. –  May 01 '17 at 11:57

1 Answers1

0

As @LotPings said:

If the first two if don't trigger program flow leads directly to :home, so what? Also after the pause, it continues with all other labels. There is an equal sign missing in the set /p test= The last assertion with c and w is nonsense.

First problem's solution: add a goto statement to re-ask to user for a valid answer.

Second problem's solution: I don't think I need to explain much...


By the way, here's the correct code:

:prompt

set /p test=Enter option:
if "%test%" == "x" goto home
if "%test%" == "y" goto home2

goto :prompt

:home
echo hi
pause

:home2
echo how are you
pause

:pie
echo want some pie?
pause