我想从用户那里获取输入并将其存储在变量中,以便将其传递给另一个函数。
先谢谢了。
答案 0 :(得分:2)
根据IO module manual,您可以使用io:fread/2,io:get_chars/2,io:get_line/1或io:read/1。 例如:
% get input in desired form in string and you need to parse it.
% each ~ts means that I want a unicode string.
1> {ok, [FirstName, LastName]} = io:fread("what is your name? ", "~ts ~ts").
what is your name? foo bar
{ok,["foo","bar"]}
2> FirstName.
"foo"
3> LastName.
"bar"
% get input for defined length in string and you need to parse it:
4> NumberOfCharacters = 7.
7
5> FullName = io:get_chars("what is your name? ", NumberOfCharacters).
what is your name? foo bar
"foo bar"
6> FullName.
"foo bar"
% get whole line as input in string and you need to parse it:
7> FullName2 = io:get_line("what is your name? ").
what is your name? foo bar
"foo bar\n"
8> FullName2.
"foo bar\n"
% get Erlang terms as input:
9> {ok, {FirstNameAtom, LastNameAtom}=FullNameTuple} = io:read("what is your name? ").
what is your name? {foo, bar}.
{ok,{foo,bar}}
10> FirstNameAtom.
foo
11> LastNameAtom.
bar
12> FullNameTuple.
{foo,bar}
13> {ok, Input} = io:read("enter text? ").
enter text? {100,c}.
{ok,{100,c}}
14> Input.
{100,c}
答案 1 :(得分:1)
1> {ok, [T]} = io:fread("enter text: ", "~s").
enter text: {100,c}
{ok,["{100,c}"]}
2> T.
"{100,c}"
然后您将获得所需的值,如下所示:
5> {ok, Tokens, _} = erl_scan:string(T).
{ok,[{'{',1},{integer,1,100},{',',1},{atom,1,c},{'}',1}],1}
6> Tokens.
[{'{',1},{integer,1,100},{',',1},{atom,1,c},{'}',1}]
7>{_, _, A1} = lists:nth(2, Tokens).
{integer,1,100}
8> {_, _, A2} = lists:nth(4, Tokens).
{atom,1,c}
9> {A1, A2}
{100, c}