【问题标题】:Block spaces between characters cmd batch字符cmd批处理之间的块空格
【发布时间】:2017-10-24 19:42:16
【问题描述】:

我正在创建简单的批处理文件,允许用户输入一些内容,然后在屏幕上显示该用户输入。目前的情况差不多是这样的:

echo off
:first
cls
set userinput=
set /p userinput=Enter anything:
if not %userinput%==[%1]==[] goto valid
echo You entered nothing or spaces only
timeout /t 2 /nobreak >nul
goto first
:valid
set userinput=%userinput: =%
echo You entered this text - %userinput%
pause >nul

此批次不允许用户输入任何内容或仅输入空格。但它允许输入空格,然后输入文本。或文本,然后是空格。或空格-文本-空格。批次越过有效扇区后,所有这些空格都将被删除,因此用户只能看到真实文本。
问题是,如果用户输入文本然后输入空格并再次输入文本,批处理就会崩溃,它会关闭。有没有简单的解决方案来阻止字符之间的空格?还是完全阻塞空间?

【问题讨论】:

  • 对字符串进行 IF 比较的正确方法是在变量和字符串周围使用引号。 IF "%var%"=="blue" echo yes
  • 这真的是有效的脚本吗? if not %userinput%==[%1]==[]
  • 是的,它有效。 if not %userinput%=="%1"=="" 也可以。
  • 你认为这样的表达是什么意思。是合乎逻辑的OR 还是AND
  • %userinput%==[%1]==[] 无效有效。如果userinput 为空,则表达式被评估为[%1]==[],有趣的是忽略了前导==,表达式被评估为true,但由于我们有if NOTif。如果userinput 不为空(比如hello)但它匹配%1,则表达式被评估为hello==[hello]==[]hello not 等于 [hello]==[] 因此表达式被评估为 false ,但由于我们有 if NOT iftrue我>。如果您将%1 更改为jello(或其他任何内容),那么您仍然拥有if true

标签: batch-file cmd spaces


【解决方案1】:

删除空格,然后检查输入。

set /p userinput=Enter anything:
SET "userinput=%userinput: =%"
if not "%userinput%" EQU "" goto valid
echo You entered nothing or spaces only
timeout /t 2 /nobreak >nul
goto first
:valid
echo You entered this text - %userinput%
pause >nul

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2021-09-04
    • 2013-09-19
    相关资源
    最近更新 更多