How can i parse the standard input with the erlang

2019-05-28 17:21发布

I'm developing a game in Erlang, and now i need to read the standard input. I tried the following calls:

io:fread() 
io:read()

The problem is that i can't read a whole string, when it contains white spaces. So i have the following questions:

  1. How can i read the string typed from the user when he press the enter key? (remember that the string contains white spaces)
  2. How can i convert a string like "56" in the number 56?

标签: erlang
3条回答
ら.Afraid
2楼-- · 2019-05-28 17:59

The console is not really a good place to do your stuff, because you need to know in advance the format of the answer. Considering that you allow spaces, you need to know how many words will be entered before getting the answer. Knowing that, you can use a string as entry, and then parse it later:

1> io:read("Enter a text > ").
Enter a text > "hello guy, this is my answer :o)".
{ok,"hello guy, this is my answer :o)"}
2>

The bad news is that the user must enter the quotes and a final dot, not user friendly...

查看更多
霸刀☆藐视天下
3楼-- · 2019-05-28 18:06

Read line

You can use io:get_line/1 to get string terminated by line feed from console.

3> io:get_line("Prompt> ").
Prompt> hello world how are you?
"hello world how are you?\n"

io:read will get you erlang term, so you can't read a string, unless you want to make your users wrap string in quotes.

Patterns in io:fread does not seem to let you read arbitrary length string containing spaces.

Parse integer

You can convert "56" to 56 using erlang:list_to_integer/1.

5> erlang:list_to_integer("56").
56

or using string:to_integer/1 which will also return you the rest of a string

10> string:to_integer("56hello").
{56,"hello"}
11> string:to_integer("56").     
{56,[]}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-05-28 18:12

The erlang documentation about io:fread/2 should help you out.

You can use field lengths in order to read an arbitrary length of characters (including whitespace):

io:fread("Prompt> ","~20c").
Prompt> This is a sentence!!
{ok,["This is a sentence!!"]}   

As for converting a string (a list of characters) to an integer, erlang:list_to_integer/1 does the job:

7> erlang:list_to_integer("645").
645

Edit: try experimenting with io:fread/2, the format sequence can ease the parsing of data by applying some form of pattern matching:

9> io:fread("Prompt> ","~s ~s").
Prompt> John Doe
{ok,["John","Doe"]}
查看更多
登录 后发表回答