Formatted output using WritelnFormat
The easiest way to output information to the output window is to use the write/writelnprocedure. As you know tt has the following form:
writeln(a, b, c, ...);
where a, b, c — are expressions of different types. This is useful if you want to output a small number of expressions without worrying about the exquisite format.
Example
Suppose we need to print the value of some function with two arguments in the following format:
f(x, y) = z
Let f be, for example, the sum of squares. Then for x = 3, y = 4the output should be:
f(3, 4) = 25 ← (3^2 + 4^2)
How can we do it with writeln? We need to write :
writeln('f(', x, ', ', y, ') = ', z);
It is not very convenient. Note that in the required string «f(x,_y)_=_z» (spaces are underlined) x, y and z are expressions, and everything else is a character that allows you to "beautifully" display these expressions.
Formatted output using WritelnFormat
It is convenient to use so-called formatted output. Let's consider an example. Instead of writeln we will use WritelnFormat:
WritelnFormat('f({0}, {1}) = {2}', x, y, z);
The first parameter ('f({0}, {1}) = {2}') is a format string which shows the format of expression output. If we want to print:
f(x, y) = z
you just need to replace x, y, z with
{0}, {1}, {2}.
Expression {N} denotes the N-th argument of WritelnFormat and is replaced by the corresponding argument value. That is, {0} in our case corresponds to x, {1} corresponds to y and so on.
Operator WritelnFormat('Hello, world!') is similar to Writeln('Hello, world!').
Operator
WritelnFormat('{0} + {1} = {1} + {0} = {2}', x, y, x + y)
works as following:
As you can see, the {N} argument can be used more than once in a format string. A similar output with writeln would look like this:
writeln(x, ' + ', y, ' = ', y, ' + ', x, ' = ', x + y);
For x = 3 and y = 5 the result will be: 3 + 5 = 8.
Note that the expressions x, y have to be specified twice.
{0.5 points}[Task-00-format.pas]. A two-digit integer is given. Output the multiplication of its digits in the following format:
'please, enter two-digit number'input: 53
output: 5 ' * ' 3 ' = ' 15
{0.5 points}[Task-01-format.pas]. A two-digit integer is given. Output the minimum of its digits in the following format:
'please, enter two-digit number'input: 64
output: 'the minimum of ' 6 ' and ' 4 'digits = ' 4
You can specify the width (W) of the output field of the expression N (width in characters): {N,W}. For example, the operator
WritelnFormat('x = *{0,5}*', x); // 5 means 5 charecters for displaying x
works this way:
x = * 6*
x = * -3*
x = * 123*
x = *-9876*
In addition to width you can also specify: alignment (right or left), format (decimal, hexadecimal, ...), the number of decimal places in real numbers, etc.
For more information about the possibilities of format output you can see here.