如何在Julia中从正在运行的脚本请求用户输入?在MATLAB中,我会这样做:
result = input(prompt)
由于
答案 0 :(得分:24)
最简单的事情是readline(stdin)
。这就是你要找的东西吗?
答案 1 :(得分:15)
正如@StefanKarpinski指出的那样,未来将会解决这个问题,这就是我现在所做的事情:
julia> @doc """
input(prompt::String="")::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::String="")::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::String="")::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>
答案 2 :(得分:1)
现在在 Julia 1.6.1 中,就像输入一样简单:
num = readline()
是的!没有任何参数,因为readline() 函数的 IO 位置参数的默认值是“stdin”。因此,在上面的示例中,Julia 将读取用户的输入并将其存储在变量“num”中。
答案 3 :(得分:0)
检查提供的答案是否与预期的类型匹配的功能:
函数定义:
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:");
答案 4 :(得分:-6)
首先我跑了 Pkg.add( “日期”) 然后
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)