2

I want to take input from user and store it in a variable so that I pass this to another function.

Thanks in advance..

Jagan
  • 41
  • 4

2 Answers2

2

According to IO module manual you can use io:fread/2, io:get_chars/2, io:get_line/1 or io:read/1. For example:

% 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}

Pouriya
  • 1,626
  • 11
  • 19
1
1> {ok, [T]} = io:fread("enter text: ", "~s").
enter text: {100,c}
{ok,["{100,c}"]}
2> T.
"{100,c}"

Then you can get needed values like this:

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}
asyndrige
  • 572
  • 6
  • 23