我该如何在Julia中从正在运行的脚本请求用户输入?在MATLAB中,我会这样做:
result = input(prompt)
谢谢
最简单的方法是readline(stdin)
。这是否是您要寻找的内容?
我喜欢这样定义:
julia> @doc """
input(prompt::AbstractString="")::String
Read a string from STDIN. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
""" ->
function input(prompt::AbstractString="")::String
print(prompt)
return chomp(readline())
end
input (generic function with 2 methods)
julia> x = parse(Int, input());
42
julia> typeof(ans)
Int64
julia> name = input("What is your name? ");
What is your name? Ismael
julia> typeof(name)
String
help?> input
search: input
input(prompt::AbstractString="")::String
Read a string from STDIN. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a trailing newline before reading input.
julia>
一个检查所提供答案是否与预期类型匹配的函数:
函数定义:
function getUserInput(T=String,msg="")
print("$msg ")
if T == String
return readline()
else
try
return parse(T,readline())
catch
println("Sorry, I could not interpret your answer. Please try again")
getUserInput(T,msg)
end
end
end
函数调用(使用方法):
sentence = getUserInput(String,"Write a sentence:");
n = getUserInput(Int64,"Write a number:");
num = readline()
没错!由于readline()函数的IO位置参数的默认值是"stdin",所以在上面的例子中,Julia将从用户那里读取输入并将其存储在变量"num"中。
首先我运行了 Pkg.add("Dates") 然后
using Dates
println()
print("enter year "); year = int(readline(STDIN))
print("enter month "); month = int(readline(STDIN))
print("enter day "); day = int(readline(STDIN))
date = Date(year, month, day)
println(date)
stdin
。 - niczky12