Lesson 5 · 5 of 20
Reading from the keyboard · Pascal
Ask the user for data with ReadLn in Pascal: text and numbers, one per line or several on the same line, to work out the price of cinema tickets.

`ReadLn` waits for the user to type a line and press Enter, and stores what they typed in the variable you pass it: ReadLn(name). It is preceded by Write, with no line break, so the question and the answer share a line.
In this example the answers come from the input.txt file, as if someone were typing them; that is why they do not appear in the output and each question is followed straight away by the program's reply. In the DMarlon Studio console (Console target, F9) you can type them yourself.
Unlike some languages, ReadLn converts the text to the variable's type: with age: Integer it reads a whole number, and with price: Double a number with decimals. If the user types something that is not a number, the program stops with a run-time error (number 106).
`ReadLn(first, second)` reads several numbers from the same line, separated by spaces, such as 7 9. They are used to work out the average mark, (first + second) / 2, printed with one decimal.
Code · main.pas
program main;var name: String; age, tickets, first, second: Integer; price: Double;begin Write('What is your name? '); ReadLn(name); WriteLn('Nice to meet you, ', name, '!'); // ReadLn turns the text into the type of the variable. Write('How old are you? '); ReadLn(age); WriteLn('In 10 years you will be ', age + 10, '.'); Write('Price of a cinema ticket? '); ReadLn(price); Write('How many tickets? '); ReadLn(tickets); WriteLn(tickets, ' tickets cost ', price * tickets:0:2, ' euros.'); // Several numbers on the same line, separated by spaces. Write('Your two exam marks? '); ReadLn(first, second); WriteLn('Average mark: ', (first + second) / 2:0:1);end.Input (what gets typed) · input.txt
Lucia 29 8.50 3 7 9
Output · fpc main.pas && ./main
What is your name? Nice to meet you, Lucia! How old are you? In 10 years you will be 39. Price of a cinema ticket? How many tickets? 3 tickets cost 25.50 euros. Your two exam marks? Average mark: 8.0
Key points
ReadLn(variable)reads a line from the keyboard.ReadLnconverts the text to the variable's type.WritebeforeReadLnkeeps the question on the same line.ReadLn(a, b)reads several numbers separated by spaces.
Exercise
Also ask for the film's title and finish with a sentence such as «3 tickets for Dune cost 25.50 euros.». Add the answer to input.txt in the right place.