2012-06-03 16 views
8

मैं interviewstreet के माध्यम से erlang सीखने की कोशिश कर रहा हूं। मैं बस भाषा सीख रहा हूं इसलिए मुझे लगभग कुछ नहीं पता है। मैं सोच रहा था कि stdin से कैसे पढ़ना है और stdout लिखना है।एरलांग पढ़ें stdin लिखें stdout

मैं एक साधारण प्रोग्राम लिखना चाहता हूं जो "हैलो वर्ल्ड!" लिखता है stdin में प्राप्त समय की संख्या।

6 

stdout के लिए लिखें::

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

आदर्श रूप में मैं एक बार (हालांकि यह इस मामले में सिर्फ एक अंक है) पर stdin एक पंक्ति पढ़ा जाएगा तो

तो stdin इनपुट के साथ

मुझे लगता है कि मैं 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. 
संबंधित मुद्दे