How to read integer in Erlang?

后端 未结 5 1323
一生所求
一生所求 2021-01-13 01:57

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.

相关标签:
5条回答
  • 2021-01-13 02:24

    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.

    string:to_integer(String) -> {Int,Rest} | {error,Reason}
    

    An example:

    {Int, Rest} = string:to_integer("33t").
    Int.  % -> 33
    Rest. % -> "t"
    

    Why check? If the user's finger slipped and hit 't' instead of 5, then the intended input was 335, not 33.

    0 讨论(0)
  • 2021-01-13 02:26
    1> {ok, [X]} = io:fread("input : ", "~d").
    input : 10
    {ok,"\n"}
    2> X.
    10
    3> {ok, [A,B]} = io:fread("input : ", "~d,~d").
    input : 456,26
    {ok,[456,26]}
    

    That's all.

    0 讨论(0)
  • 2021-01-13 02:26

    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.

    0 讨论(0)
  • 2021-01-13 02:34

    Try printing the number with ~w instead of ~p:

    1> io:format("~w~n", [[10]]).
    [10]
    ok
    2> io:format("~p~n", [[10]]).
    "\n"
    ok
    

    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.

    0 讨论(0)
  • 2021-01-13 02:50

    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 the string module:

    string:to_integer(String) -> {Int,Rest} | {error,Reason}
    

    There is also the list_to_integer(String) BIF (Built-In Function, just call without a module) but it is not as forgiving as the string:to_integer(String) function:

    list_to_integer(String) -> int()
    

    You will get a badarg exception if the string does not contain an integer.

    0 讨论(0)
提交回复
热议问题