Erlang读stdin写stdout [英] Erlang read stdin write stdout
问题描述
我正在尝试通过 interviewstreet 学习erlang。我只是现在学习语言,所以几乎什么都不知道。我想知道如何从stdin读取并写入stdout。
I'm trying to learn erlang through interviewstreet. I just learning the language now so I know almost nothing. I was wondering how to read from stdin and write to stdout.
我想编写一个写Hello World!的简单程序。在stdin中收到的次数。
I want to write a simple program which writes "Hello World!" the number of times received in stdin.
所以用stdin输入:
So with stdin input:
6
写入stdout:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
理想情况下,我会一次阅读stdin一行(尽管在这种情况下只是一位数) )所以我想我将使用get_line。
Ideally I will read the stdin one line at a time (even though it's just one digit in this case) so I think I will be using get_line. That's all I know for now.
谢谢
谢谢
推荐答案
这是另一个解决方案,也许更有用。
Here's another solution, maybe more functional.
#!/usr/bin/env escript
main(_) ->
%% Directly reads the number of hellos as a decimal
{ok, [X]} = io:fread("How many Hellos?> ", "~d"),
%% Write X hellos
hello(X).
%% Do nothing when there is no hello to write
hello(N) when N =< 0 -> ok;
%% Else, write a 'Hello World!', and then write (n-1) hellos
hello(N) ->
io:fwrite("Hello World!~n"),
hello(N - 1).
这篇关于Erlang读stdin写stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!