如何在 Erlang 中读取整数?
我正在尝试读取用户输入的整数。 (如 C++ 中的 cin >> nInput;)
我从 http://www.erlang.org/doc/man/ 找到了 io:fread bif io.html,所以我写这样的代码。
{ok, X} = io:fread("输入:", "~d"),
io:format("~p~n", [X]).
但是当我输入 10 时,erlang 终端一直给我 "\n" 而不是 10。我假设 fread自动读取 10 并将其转换为字符串。 如何直接读取整数值? 有什么办法可以做到这一点吗? 谢谢您阅读此篇。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
就这样。
That's all.
OTP 中有多种函数可以帮助您将字符串转换为整数。 如果您只是从用户那里读取一个字符串(例如直到换行符),您可以使用
string
模块中的函数to_integer(String)
对其进行评估:还有
list_to_integer(String)
BIF(内置函数,无需模块即可调用),但它不像string:to_integer(String)
函数那样宽容:您将得到如果字符串不包含整数,则会出现
badarg
异常。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.如果使用 string:to_integer/1,请检查 Rest 的值为空列表 []。 该函数从字符串的开头提取整数(如果有)。 它不保证完整输入转换为整数。
举个例子:
为什么要检查? 如果用户手指滑动并点击“t”而不是 5,则预期输入是 335,而不是 33。
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.
尝试使用
~w
而不是~p
打印数字:~p
格式说明符尝试确定列表是否可能是字符串,但~w
永远不会猜测; 它总是将列表打印为列表。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 将字符串表示为特定范围内的整数列表。 因此,输入将是代表字符“1”的数字,您可以减去偏移量以获得实际值。 抱歉,这里没有虚拟机来测试解决方案。
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.