Menu
CoddyTech

Reading Input with readline()

Part of the Fundamentals section of Coddy's R journey. Lesson 29 of 78.

So far, you've learned how to display output. Now it's time to make your programs interactive by reading input from the user. The readline() function lets you capture what the user types.

name <- readline()
cat("Hello,", name, "\n")

When this code runs in an interactive R session (the R console or RStudio), R waits for the user to type something and press Enter. Whatever they type gets stored in the name variable. If the user types "Alice", the output would be: Hello, Alice

On this platform your code runs as a script with Rscript, so readline() does not wait: it returns an empty string "" right away. That is why the starter code of this lesson's challenge reads its input with readLines() instead.

One important thing to know: readline() always returns a character string, even if the user types a number. If someone enters "25", it's stored as the text "25", not the number 25. You'll learn how to convert between types in the next lesson.

You can read multiple inputs by using readline() multiple times:

first <- readline()
second <- readline()
cat("First:", first, "\n")
cat("Second:", second, "\n")

In an interactive session, each readline() call waits for a separate line of input from the user.

When combining text with variables using cat(), each item separated by a comma gets a space between it. Sometimes you need to join text without any space, for example, to attach punctuation directly to a word. That's where paste0() is useful. It concatenates strings with no separator between them:

city <- readline()
cat("Welcome to", paste0(city, "!"), "\n")

Here, paste0(city, "!") joins the value of city and "!" together with no space, so if the user types "Paris", the output is: Welcome to Paris!

challenge icon

Challenge

Easy

Read two lines of input and display a personalized greeting message.

You will receive two inputs:

  1. A first name
  2. A city name

The starter code already reads both inputs into name and city with readLines(), because readline() only works in an interactive session and gets nothing here. Display a message in the following format:

Welcome, [name] from [city]!

Use cat() to produce the output. Make sure to include the exclamation mark at the end and a newline character \n.

For example, if the inputs are Emma and Paris, the output should be:

Welcome, Emma from Paris!

Try it yourself

# Read input
con <- file("stdin", "r")
name <- suppressWarnings(readLines(con, n = 1))
city <- suppressWarnings(readLines(con, n = 1))

# TODO: Write your code below to display the greeting message
# Use cat() to output: Welcome, [name] from [city]!
# Don't forget the newline character \n at the end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online R compiler