ejang
ejang

Reputation: 4062

Julia request user input from script

How do I request user input from a running script in Julia? In MATLAB, I would do:

result = input(prompt)

Thanks

Upvotes: 33

Views: 17747

Answers (5)

winterr_dog
winterr_dog

Reputation: 89

Now in Julia 1.6.1, it's as simple as typing:

num = readline()

Yea! without any arguments since the default value for the IO positional argument of the readline() function is "stdin". So in the above example Julia will read the input from the user and store it in the variable "num".

Upvotes: 4

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

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>

Upvotes: 19

Antonello
Antonello

Reputation: 6423

A function that checks that the answer provided matches the expected Type:

Function definition:

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

Function call (usage):

sentence = getUserInput(String,"Write a sentence:");
n        = getUserInput(Int64,"Write a number:");

Upvotes: 2

John Myles White
John Myles White

Reputation: 2929

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

Upvotes: 35

Barry Andersen
Barry Andersen

Reputation: 609

First I ran Pkg.add("Dates") then

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)

Upvotes: -4

Related Questions