Interactive input

I have a program saved in a .R file. One of the challenges I have with it is that I have a statement that is supposed to read data from the keyboard which is not working. The statement is

num_itr <- scan(file = "", what = numeric(), n = 1, quiet = TRUE)

However, instead of the program stopping for input from the keyboard, it assigned an empty numeric value to num_itr.

What should I do to overcome this or is there an alternative code that I can use to read numeric data into a program running from a .R file?

Try changing file = "" to file = "stdin". According to the help documentation for scan, those should be equivalent, but on my system the latter works and former does not.

Thank you for your response. It actually work in that R stopped and was blinking for an input. However, the challenge is that after typing one numerical value to be read n = 1 being what was set, the program continued blinking in a manner that suggests it was waiting for more inputs. I tried stopping the operation by clicking the "interrupt" button. This equally failed to stop R and I had to choose the option of terminating R completely. This has happened twice.

I hope you may have other suggestion. Otherwise, your time is very much appreciated.

On my system (Linux Mint), ctrl-D will tell the script to stop waiting for input and move ahead (if possible).

I put the following code in a script (.R) file, ran it in a terminal with the Rscript command, and it behaved as expected. Does it work for you?

cat("Enter a number: ")
num_itr <- scan(file = "stdin", what = numeric(), n = 1, quiet = TRUE)
cat("The number entered is ", num_itr, "\n")

Created on 2025-12-29 with reprex v2.1.1