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:
- How can i read the string typed from the user when he press the enter key? (remember that the string contains white spaces)
- How can i convert a string like "56" in the number 56?
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:
The bad news is that the user must enter the quotes and a final dot, not user friendly...
Read line
You can use
io:get_line/1
to get string terminated by line feed from console.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"
to56
usingerlang:list_to_integer/1
.or using
string:to_integer/1
which will also return you the rest of a stringThe 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):
As for converting a string (a list of characters) to an integer, erlang:list_to_integer/1 does the job:
Edit: try experimenting with io:fread/2, the format sequence can ease the parsing of data by applying some form of pattern matching: