Home > Mobile >  How to use ENTER as user input
How to use ENTER as user input

Time:06-20

I have a for loop and I want it to only go to the next "i"-value when you hit enter in the console. So I wrote this:

for (i in 1:5){
 print(i) 
 UserInput <- readline(prompt = "Press enter to continue.")
 if (UserInput != "ENTER"){ #Obviously "ENTER" is incorrect, but something like that. 
  break
 }
}

Any clues?

CodePudding user response:

A simple solution is:

for (i in 1:5){
    readline(prompt=i) }

CodePudding user response:

This approach will prompt the user to press enter, and will go to the next i when they do so:

for (i in 1:5){
    print(i) 
    readline(prompt = "Press Enter")
}
# [1] 1
# Press Enter
# [1] 2
# Press Enter
# [1] 3
# Press Enter
# [1] 4
# Press Enter
# [1] 5
# Press Enter

If you want the first result (1) to show only after an "enter", then just swap the two lines, print and readline.

Edit: based on comment, you can break if something other than an "enter" was input

for (i in 1:5){
  print(i) 
  input <- readline(prompt = "Press Enter")
  if(input != "") break
}
  • Related