【问题标题】:Erlang read stdin write stdoutErlang 读标准输入 写标准输出
【发布时间】:2012-06-08 00:44:04
【问题描述】:

我正在尝试通过interviewstreet 学习erlang。我现在只是学习语言,所以我几乎一无所知。我想知道如何从标准输入读取并写入标准输出。

我想写一个简单的程序来写“Hello World!”在标准输入中接收的次数。

所以使用标准输入:

6

写入标准输出:

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

理想情况下,我将一次读取一行标准输入(即使在这种情况下它只是一位数字),所以我想我将使用 get_line。这就是我目前所知道的。

谢谢

谢谢

【问题讨论】:

    标签: erlang stdout stdin getline


    【解决方案1】:

    这是另一种解决方案,可能更实用。

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

      这是我的尝试。我使用了 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)
          ).
      

      【讨论】:

        【解决方案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.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-25
          • 1970-01-01
          • 2019-09-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-31
          • 2013-09-18
          相关资源
          最近更新 更多