Reading input (stdin)

Read what you type in the IDE's Input tab with readLines(file("stdin")) or scan().

Runs in Zerethon IDE · R 4.5 Official R documentation ↗

A run cannot ask questions while it runs. Type the script's input in the Input tab before you press Run; the script reads it from file("stdin").

main.R
con <- file("stdin")
lines <- readLines(con)
close(con)
name <- lines[1]
nums <- as.integer(strsplit(lines[2], " ")[[1]])
cat(sprintf("Hello, %s! %d + %d = %d\n", name, nums[1], nums[2], sum(nums)))

Input (stdin)

Ada
3 4

Output

Hello, Ada! 3 + 4 = 7
main.R
numbers <- scan(file("stdin"), quiet = TRUE)
cat(sprintf("total: %g\n", sum(numbers)))

Input (stdin)

5
10
15

Output

total: 30
scan() reads every number of the input at once.

Watch out: readline() does not read input here: in a script (not the interactive console) it returns "" at once. Use readLines(file("stdin")).

Related topics

Official references