Batch error: Numeric constants are either decimal (17), hexadecimal (0x11), or octal (021)

Batch error: Numeric constants are either decimal (17), hexadecimal (0x11), or octal (021)

我正在提取两位数字并在其中加一。但是当最后两位数字是 08 时,就会抛出上述错误。

set last_two=!file_name:~-2,2!
set /a add_millisec=!last_two!+1
set add_millisec=0!add_millisec!
set add_millisec=!add_millisec:~-2!

有人可以检查并帮助我吗...

打开命令提示符 window 并键入 set /?:

[...] Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, and 0 for octal numbers. So 0x12 is the same as 18 is the same as 022. Please note that the octal notation can be confusing: 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits. [...]

您会发现 set /A 将带前导 0 的数字视为八进制数。

要克服这个问题,您可以执行以下操作:

  1. 在数字前面加上1,计算完再去掉:

    set last_two=1!file_name:~-2,2!
    set /A add_millisec=last_two+1
    set add_millisec=!add_millisec:~-2!
    

    为此你需要提前知道总位数。

  2. 在任何计算之前删除尾随零,然后根据需要用前导零填充结果:

    set last_two=!file_name:~-2,2!
    rem The following line removes all leading zeros:
    for /F "tokens=* delims=0" %%Z in ("!last_two!") do set last_two=%%Z
    set /A last_two+=0 & rem this avoids `last_two` to be empty if it is `0`
    set /A add_millisec=last_two+1
    set add_millisec=0!add_millisec!
    set add_millisec=!add_millisec:~-2!
    

    或者:

    set last_two=!file_name:~-2,2!
    rem The following two lines remove all leading zeros:
    cmd /C exit !last_two!
    set /A last_two=!ErrorLevel!
    set /A add_millisec=last_two+1
    set add_millisec=0!add_millisec!
    set add_millisec=!add_millisec:~-2!
    

    这种方法比较灵活,因为你不知道位数。