ja_vole
ja_vole

Reputation: 11

Erlang and io:read()

I have a problem, I don't know why the program doesn't work correctly. When I run the program and I insert atom c, then the program calls function io:read() forever.

Thank you for your help and I'm sorry for my English.

-module(temperature).
-export([run/0, convert/2]).

run() ->
   run(true).

run(true) ->
  {ok, Choice} = io:read("Convert to degrees Celsius or convert to degrees Fahrenheit? c/f :"),
  {ok, Temp} = io:read("Insert temperature: "),
  {UnitTemp, Convert} = convert(Choice, Temp),
  io:format("The converted temperature: ~f ~s\n", [Convert, UnitTemp]),
  {ok, Continue} = io:read("New temperature? true/false :"),
  run(Continue);

run(false) ->
  ok.

convert(c, Fahrenheit) -> {'Celsius', 5 * (Fahrenheit - 32) / 9};
convert(f, Celsius) -> {'Fahrenheit', 9 * Celsius / 5 + 32}.

Upvotes: 0

Views: 815

Answers (1)

tkowal
tkowal

Reputation: 9289

io:read reads a term, so it does not stop, until you finish your term with ..

1> io:read("Enter term: ").
Enter term: {foo, bar}.
{ok,{foo,bar}}
2> io:read("This will give error: ").
This will give error: }foo
This will give error: .
{error,{1,erl_parse,["syntax error before: ","'}'"]}}

So you can simply type c..

Alternatively, you can use io:get_chars/2 if you don't want to type the dot. The first argument is prompt and second one is number of chars to read, so in your case, it will be:

io:get_chars("prompt ", 1).
prompt c
"c"

Remember, that after typing c, you still have to hit enter and now, you should pattern match on string "c" instead of atom c.

Upvotes: 1

Related Questions