6

I'm trying to write a batch file that performs operations depending on the result of a modulus operation performed on a set variable. However, I can't seem to get it quite right.

To first of all test my syntax for the mathematical operation, I've been trying to get a simpler script to produce desired results.

:START
SETLOCAL
SET /P Input-Num="Input Number: "
SET /A Input-Num=%Input-Num% %% 2
ECHO %Input-Num%
ENDLOCAL
PAUSE 
:END

If I input 5, the expected output is 1. However, instead I get a message saying Missing operator. and then it outputs 5.

What am I doing wrong here?

Iszi
  • 777
  • 3
  • 12
  • 26
  • Is this DOS or something else? I get `1` with no `Missing operator` when I run that exact sample (with `@ECHO OFF` added at the top) – LittleBobbyTables - Au Revoir Jul 17 '12 at 18:39
  • 2
    Your code works fine when from from a batch file. If you are typing it directly into CMD then don't escape the `%`. use `%` instead of `%%`. – vcsjones Jul 17 '12 at 18:42
  • @LittleBobbyTables First off, I love your screen name. It's in CMD on Windows 7. I've updated the tags. – Iszi Jul 17 '12 at 18:51
  • @vcsjones I'll try it again, but I've been running it as a batch file the whole time. Perhaps the only significant difference is I've been using `SET /P` for the first variable setting. – Iszi Jul 17 '12 at 18:52
  • Updated question to reflect `SET /P`. – Iszi Jul 18 '12 at 15:01

1 Answers1

4

Using SET /P is your problem, as 5 is no longer treated as a numerical value. Your example as above works as expected

LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
  • Is there a way to use `SET /P` (or something that would operate similarly) *and* perform math operations on the variable? – Iszi Jul 17 '12 at 20:11
  • See this link: http://stackoverflow.com/a/684389/334849. They use `SET /P`, then do `SET /A` for a second variable later in the code. – LittleBobbyTables - Au Revoir Jul 17 '12 at 20:22
  • Tried that now. Still doesn't work. Now I get *two* `Missing operator` errors. – Iszi Jul 18 '12 at 15:02
  • Already did. I figured it out now. Apparently, having dashes in variable names (yeah, I was using different variable names) doesn't mix well with performing math on those variables. (Edited those in now, too.) – Iszi Jul 18 '12 at 15:05
  • NOTE: I pulled extra variable and set it up to work directly with the input, and it works now that I've removed the dashes from the variable names. – Iszi Jul 18 '12 at 15:09