如何让用户输入变量?

时间:2014-12-21 19:01:03

标签: batch-file

如何让用户输入变量? (我不知道这是因为我正在进行设置......)

例如,如果用户的输入是"输入"我可以创建一个用户输入的变量吗?如果用户的输入是" 3"变量为3.如果用户(或答案)的输入为4,则变量为4。

代码:

:loop
set /p input=input something here: 
if %input%==. goto loop
if not %input%==. goto store_userinput_as_variable
:store_userinput_as_variable
cls
echo Your input has been stored in a variable.

但是我如何制作一个用户输入的变量?请帮忙!

2 个答案:

答案 0 :(得分:0)

以下是使用批处理文件的用户输入名称创建环境变量的示例。

@echo off
setlocal EnableDelayedExpansion
:Loop
rem Define environment variable "input" with a double quote as default value.
rem This is necessary to avoid an execution break after user input because of
rem not defined "input" variable in case of user just hits RETURN or ENTER on
rem prompt without entering anything.
set "input=""
set /p "input=Input something here: "
rem Remove all double quotes, left and right angle brackets entered by the user.
set "input=%input:"=%"
set "input=%input:<=%"
set "input=%input:>=%"
rem Has the use entered anything at all?
if "%input%"=="" goto Loop
set "%input%=This variable name was entered by the user."
echo Your input has been stored in a variable.
set "%input%"
endlocal

但我不推荐这个。这是非常危险的,因为用户可以输入具有特殊含义的字符,导致批处理退出,因为语法错误或更糟糕的批处理执行操作。

例如,如果批处理用户输入以等号开头的字符串,则此代码将导致进一步处理时出现语法错误。 Critical也是用户输入的字符串,是一个重要的预定义环境变量的名称,如 PATHEXT PATH APPDATA USERNAME ,...

我强烈建议不要做你现在想做的事。对我们来说,为什么要创建一个具有批处理文件用户输入的名称的环境变量会很有趣。

答案 1 :(得分:0)

我不确定你想要完成什么,但也许这会有所帮助。

@ECHO OFF   

:loop
set /p input=input something here: 
if %input%==. goto loop
if not %input%==. goto store_userinput_as_variable
:store_userinput_as_variable
cls

ECHO You entered: %input%

REM Create a variable with the same name as the value they entered.
CALL SET %input%=New Variable

CALL ECHO The variable "%input%" has a value of "%%%input%%%"

因此,如果输入&#34; Hello&#34;,输出将为:

You entered: Hello
The variable "Hello" has a value of "New Variable"