I'm trying to read user input of integer. (like cin >> nInput; in C++)
I found io:fread bif from http://www.erlang.org/doc/man/io.html, so I write code like this.
{ok, X} = io:fread("input : ", "~d"),
io:format("~p~n", [X]).
but when I input 10, the erlang terminal keep giving me "\n" not 10. I assume fread automatically read 10 and conert this into string. How can I read integer value directly? Is there any way to do this? Thank you for reading this.
Try printing the number with
~w
instead of~p
:The
~p
format specifier tries to figure out whether the list might be a string, but~w
never guesses; it always prints lists as lists.Erlang represents strings as lists of integers that are within a certain range. Therefore the input will be a number that represents the character "1" you could subtract an offset to get the actual. Number, sorry don't have a VM here to test a solution.
There are various functions in OTP to help you convert a string to an integer. If you just read a string from the user (until newline for example) you can the evaluate it with the function
to_integer(String)
in thestring
module:There is also the
list_to_integer(String)
BIF (Built-In Function, just call without a module) but it is not as forgiving as thestring:to_integer(String)
function:You will get a
badarg
exception if the string does not contain an integer.That's all.
If you use string:to_integer/1, check that the value of Rest is the empty list []. The function extracts the integer, if any, from the beginning of the string. It does not assure that the full input converts to an integer.
An example:
Why check? If the user's finger slipped and hit 't' instead of 5, then the intended input was 335, not 33.