13

私はinterviewstreetを通してerlangを学ぼうとしています。私は今言語を学んでいるだけなので、ほとんど何も知りません。stdinから読み取り、stdoutに書き込む方法を考えていました。

「HelloWorld!」と書く簡単なプログラムを書きたいです。stdinで受信された回数。

したがって、stdin入力を使​​用すると:

6

stdoutに書き込みます:

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

理想的には、一度に1行ずつstdinを読み取ります(この場合は1桁ですが)ので、get_lineを使用すると思います。今のところ私が知っているのはそれだけです。

ありがとう

ありがとう

4

3 に答える 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).
于 2012-06-03T19:30:31.273 に答える
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) ].

リスト内包表記を使用したくない場合、これは、lists: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)
    ).
于 2012-06-03T19:18:30.470 に答える
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.
于 2017-04-04T18:48:31.397 に答える