Erlang read stdin write stdout
Asked Answered
G

3

13

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

Guttering answered 3/6, 2012 at 18:43 Comment(0)
P
24

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).
Prompter answered 3/6, 2012 at 19:30 Comment(0)
B
1

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)
    ).
Burr answered 3/6, 2012 at 19:18 Comment(0)
G
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.
Genovese answered 4/4, 2017 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.