2012-06-03 44 views
8

我想通過interviewstreet來學erlang。我現在只是學習語言,所以我幾乎什麼都不知道。我想知道如何從標準輸入讀取並寫入標準輸出。Erlang讀stdin寫stdout

我想寫一個簡單的程序寫「Hello World!」標準輸入接收的次數。

因此,與標準輸入輸入:

6 

寫入stdout:

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

理想的情況下,我會一次讀取(即使它只是一個數字在這種情況下)的標準輸入一個行,以便我想我會使用get_line。這就是我現在所知道的。

感謝

感謝

回答

19

這是另一種解決方案,也許更多的功能。

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

+1尾遞歸! – marcelog

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.