How can i parse the standard input with the erlang api?

二次信任 提交于 2019-12-12 10:08:54

问题


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?

回答1:


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,[]}



回答2:


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"]}



回答3:


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...



来源:https://stackoverflow.com/questions/19097507/how-can-i-parse-the-standard-input-with-the-erlang-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!