Erlang read stdin write stdout

假装没事ソ 提交于 2019-12-23 07:01:10

问题


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.

I want to write a simple program which writes "Hello World!" the number of times received in stdin.

So with stdin input:

6

Write to stdout:

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

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.

thanks

Thanks


回答1:


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).



回答2:


Here's my shot at it. I've used escript so it can be run from the command line, but it can be put into a module easily:

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

If you dont want to use a list comprehension, this is a similar approach to the last line of code, by using lists:foreach and the same sequence:

    % 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)
    ).



回答3:


% 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.


来源:https://stackoverflow.com/questions/10872909/erlang-read-stdin-write-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!