Getting User Input
Part of the Fundamentals section of Coddy's R journey — lesson 34 of 78.
Challenge
EasyIn 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:
- The total bill amount
- The tip percentage (as a whole number, e.g.,
15for 15%) - 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 inconreadLines(con, n = 1)— reads exactly one line from that connectionsuppressWarnings(...)— silences harmless warnings that appear when reading fromstdinthis wayas.numeric(...)— converts the text input to a numberclose(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: 4Try 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
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 27Bill Split Calculator
Welcome MessageGetting User Input2Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values