Sam
Sam

Reputation: 2331

Reading multiple words from the user/console using fread in Erlang

I want to read multiple words and store them in a variable using Erlang. When I use fread to record a string, it records only the first word.

1> {ok,[Message]} = io:fread("Type your message : ", "~ts").
Type your message : Hello world
{ok,["Hello"]}
2>  world

So "Hello" is saved to Message instead of "Hello world". How can I save both words to the variable message.

I'm looking for a general answer so that I can read in many words and not just 2 words, so please don't post answers for only 2 words.


Desired output

{ok,["Hello world"]}

Upvotes: 0

Views: 173

Answers (1)

7stud
7stud

Reputation: 48599

See io:get_line/1

1> Line = io:get_line("Type your message: ").
Type your message: Hello world. Goodbye.
"Hello world. Goodbye.\n"

2> Line.
"Hello world. Goodbye.\n"

3> DesiredOutput = {ok, [string:strip(Line, right, $\n)]}.
{ok,["Hello world. Goodbye."]}

4> DesiredOutput.
{ok,["Hello world. Goodbye."]}

Line:

The characters in the line terminated by a line feed (or end of file). If the I/O device supports Unicode, the data can represent codepoints > 255 (the latin1 range).

Upvotes: 1

Related Questions