There is only one statement that you need to use in console applications to get input from the user: the ReadLn statement. So far, we have used the ReadLn statement to pause the execution of the application. This works perfectly because the ReadLn statement waits until the user presses Enter on the keyboard. When the user presses Enter, the ReadLn statement finishes and subsequent statements get executed.
To actually read a piece of data that we can work with, we have to put whatever the user enters into a variable. The syntax for reading a value into a variable is the same as when we are displaying the value of the variable. The only difference is that for reading we use the ReadLn statement instead of WriteLn.
Listing 2-14: Reading values with ReadLn
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var UserName: string; begin Write('Enter your name: '); ReadLn(UserName); WriteLn; WriteLn('Hello, ', UserName, '!'); ReadLn; end.
The application in Listing 2-14 illustrates two things: how to read values using the ReadLn statement and how to display multiple values with one WriteLn statement. When you display multiple values with the WriteLn statement, you have to separate each item with a comma.
The last example in the Delphi portion of the chapter is a small application that calculates the full price of a product — the original product price plus shipping and handling. In this example, shipping and handling always costs 15% of the original product price. The user only has to enter the original product price and the application does the rest (see Figure 2-8).
Figure 2-8: Calculating the total cost
Listing 2-15: Working with user data
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var Price: Double; FullPrice: Double; begin Write('Product price: '); ReadLn(Price); FullPrice := Price + (Price * 15 / 100); WriteLn('Price with shipping: $', FullPrice:0:2); ReadLn; end.
There are a couple of details that can be enhanced in this code. First, we can remove the uses list since we don't use anything from the SysUtils unit (this removes some 25 KB from the executable). Second, the percentage value should be placed into a constant if we plan to do more calculations with it. Third, this simple calculation can be performed inside the WriteLn statement, so we can remove the FullPrice variable. This shorter version of the application is displayed in Listing 2-16.
Listing 2-16: A shorter version of the total cost application
program Project1; {$APPTYPE CONSOLE} var Price: Double; const SHIPPING = 1 + (15 / 100); begin Write('Product price: '); ReadLn(Price); WriteLn('Price with shipping: $', (Price * SHIPPING):0:2); ReadLn; end.