我想通过学习二郎山interviewstreet 。 我刚学的语言,所以我现在几乎一无所知。 我不知道如何从标准输入读取和写入到stdout。
我想编写一个简单的程序,写的“Hello World!” 在标准输入接收的次数。
因此,与标准输入输入:
6
写入stdout:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
理想情况下,我会一次读取(即使它是在这种情况下,只是一个数字)的标准输入一个行,所以我想我会用get_line。 这是我所知道的现在。
谢谢
谢谢
这里是另一种解决方案,也许更多的功能。
#!/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).
这里是我的投篮吧。 我用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)
).
% 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.