Julia request user input from script

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>

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".


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:");

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

Tags:

Julia