32

如何从 Julia 中的正在运行的脚本请求用户输入?在 MATLAB 中,我会这样做:

result = input(prompt)

谢谢

4

5 回答 5

34

The easiest thing to do is readline(stdin). Is that what you're looking for?

于 2013-07-05T03:53:47.133 回答
19

I like to define it like this:

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>
于 2014-04-28T13:50:57.343 回答
2

检查提供的答案是否与预期类型匹配的函数:

函数定义:

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:");
于 2019-05-10T13:57:02.930 回答
1

现在在 Julia 1.6.1 中,只需键入:

num = readline()

是的!没有任何参数,因为readline() 函数的 IO 位置参数的默认值为stdin ”。所以在上面的例子中,Julia 将读取用户的输入并将其存储在变量“ num ”中。

于 2021-07-27T10:28:13.357 回答
-4

首先我跑了 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)
于 2014-09-02T14:52:13.213 回答