0

I have the following function which requires a sequence of user inputs:

fun <- function(){ 


  cat("Hello! let's input some data")

  x <- readline("Input foo: ")
  y <- readline("Input bar: ")
  z <- readline("Input baz: ")
  a <- readline("Input foobarbaz: ")

}

fun()

However, when I call fun() after the function is defined, it often skips directly to the second input - Input bar: why is readlines() asynchronous in a function? Does it have to do with assigning the input to a variable?

In the console:

> fun()
Hello! let's input some dataInput foo: 
Input bar: 

I would like the inputs to appear in the same order as they are written in the function.

Why does this happen and what is the workaround?

iskandarblue
  • 7,208
  • 15
  • 60
  • 130
  • 2
    How often? I can't reproduce it with several tries. – Anonymous coward Apr 05 '18 at 20:42
  • 1
    See this related question https://stackoverflow.com/questions/44012056/r-how-do-i-prompt-the-user-for-input-from-the-console – iskandarblue Apr 05 '18 at 20:44
  • 1
    It might not be reproducible with a short amount of code as above, but `readline()` doesn't necessarily wait for the first input before it jumps to the next input. – iskandarblue Apr 05 '18 at 20:46
  • There doesn't appear to be any [wait function](https://stackoverflow.com/questions/29544217/waiting-for-user-input-in-r-from-terminal), but maybe depends on [how the code is run](https://stackoverflow.com/questions/39245442/wait-for-user-input-from-keyboard-in-r-before-next-line-of-code-readline-rst)? – Anonymous coward Apr 05 '18 at 20:55
  • 1
    I've found the solution here: https://stackoverflow.com/questions/27112370/make-readline-wait-for-input-in-r – iskandarblue Apr 05 '18 at 21:15

1 Answers1

1

You need to specify that the next statement goes on a new line.

cat("Hello! let's input some data", sep="\n")
Matt Salzman
  • 265
  • 2
  • 13
  • What is the new output? Please give me more to go off – Matt Salzman Apr 05 '18 at 20:30
  • The same problem persists of intermittently skipping to the second input, even after adding `sep = "\n"` – iskandarblue Apr 05 '18 at 20:31
  • OP isn't worried about which line things print on. The problem is that `readline()` is supposed to wait for user input before proceeding, but OP never gets a chance to enter the first input before the second input is requested. – Gregor Thomas Apr 05 '18 at 21:06