Menu
Coddy logo textTech

Getting User Input

Part of the Fundamentals section of Coddy's R journey — lesson 34 of 78.

challenge icon

Challenge

Easy

In the previous lesson, you created a welcome message for the Bill Split Calculator. Now, add the functionality to collect user input for the bill calculation.

After your existing welcome message, read three inputs from the user:

  1. The total bill amount
  2. The tip percentage (as a whole number, e.g., 15 for 15%)
  3. The number of people splitting the bill

In R scripts that run non-interactively (like on this platform), input is read from the standard input stream. To do this, first open a connection to stdin using file(), then read each line with readLines(), and close the connection when done:

con <- file("stdin", "r")
bill <- as.numeric(suppressWarnings(readLines(con, n = 1)))
tip_percent <- as.numeric(suppressWarnings(readLines(con, n = 1)))
people <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)

Here is what each part does:

  • file("stdin", "r") — opens the standard input stream for reading and stores it in con
  • readLines(con, n = 1) — reads exactly one line from that connection
  • suppressWarnings(...) — silences harmless warnings that appear when reading from stdin this way
  • as.numeric(...) — converts the text input to a number
  • close(con) — closes the connection after all inputs are read

Store the three values in variables named bill, tip_percent, and people.

After reading the inputs, display a confirmation message showing what was entered in the following format:

Bill: $[bill]
Tip: [tip_percent]%
People: [people]

Use cat() for all output and include newline characters \n where needed. Use sep = "" in each cat() call to avoid unwanted spaces.

For example, if the inputs are 120, 18, and 4, the complete output should be:

Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $120
Tip: 18%
People: 4

Try it yourself

# TODO: Write your code below
# Use cat() to display the welcome message
# Remember to use \n for new lines
cat("Welcome to the Bill Split Calculator!\nLet's split your bill fairly.\n")

All lessons in Fundamentals