Erlang读取标准输入并写入标准输出。

13
我正在尝试通过interviewstreet学习erlang。我现在才开始学习这种语言,所以我几乎一无所知。我想知道如何从stdin读取并写入stdout。
我想编写一个简单的程序,根据stdin接收到的次数输出"Hello World!"。
因此,使用stdin输入:
6

写入标准输出:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

理想情况下,我将一次读取stdin的一行(即使在这种情况下只有一个数字),因此我认为我将使用get_line。目前就只知道这些。

谢谢

谢谢

3个回答

24

这里有另一个解决方案,可能更具有功能性。

#!/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).

1
这是我的尝试。我使用了escript,因此它可以从命令行运行,但很容易将其放入模块中:
#!/usr/bin/env escript

main(_Args) ->
    % Read a line from stdin, strip dos&unix newlines
    % This can also be done with io:get_line/2 using the atom 'standard_io' as the
    % first argument.
    Line = io:get_line("Enter num:"), 
    LineWithoutNL = string:strip(string:strip(Line, both, 13), both, 10),

    % Try to transform the string read into an unsigned int
    {ok, [Num], _} = io_lib:fread("~u", LineWithoutNL),

    % Using a list comprehension we can print the string for each one of the
    % elements generated in a sequence, that goes from 1 to Num.
    [ io:format("Hello world!~n") || _ <- lists:seq(1, Num) ].

如果您不想使用列表推导式,这是一种类似于代码的最后一行的方法,通过使用列表:foreach和相同的序列:

    % Create a sequence, from 1 to Num, and call a fun to write to stdout
    % for each one of the items in the sequence.
    lists:foreach(
        fun(_Iteration) ->
            io:format("Hello world!~n")
        end,
        lists:seq(1,Num)
    ).

0
% Enter your code here. Read input from STDIN. Print output to STDOUT 
% Your class should be named solution

-module(solution).
-export([main/0, input/0, print_hello/1]).

main() ->
    print_hello(input()).

print_hello(0) ->io:format("");
print_hello(N) ->
    io:format("Hello World~n"),
    print_hello(N-1).
input()->
    {ok,[N]} = io:fread("","~d"),
N.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接