Input & Output
Write outputs values; Writeln also outputs a line break.
8.1 Write and Writeln
Write outputs values; Writeln also outputs a line break. Both accept any number of arguments of simple types and strings:
Write('Name: ');
Writeln('Alice', ' is ', 30, ' years old');
Writeln; // empty line8.2 Formatting with width and decimals
Value:Width right-aligns in a field; RealValue:Width:Decimals fixes the number of decimals:
Negative widths are not supported for left alignment; use Format instead.
program Formatting;
{$mode objfpc}{$H+}
var
X: Double = 3.14159;
begin
Writeln('[', 42:6, ']'); // [ 42]
Writeln('[', 'abc':6, ']'); // [ abc]
Writeln('[', X:0:2, ']'); // [3.14]
Writeln('[', X:10:3, ']'); // [ 3.142]
Writeln(X); // 3.1415899999999999E+000 (scientific by default)
Writeln(True:6); // " TRUE"
end.8.3 Format — printf-style formatting
general (shortest) number with thousands separators money (currency format) left-aligned width 10
uses SysUtils;
...
Writeln(Format('%-10s|%5d|%8.2f', ['Apple', 12, 3.5]));
// "Apple | 12| 3.50"
Writeln(Format('%x %.3d %s %%', [255, 7, 'ok'])); // "FF 007 ok %"
Writeln(Format('%1:s %0:s', ['World', 'Hello'])); // "Hello World" (argument index)8.4 Read and Readln
Read reads values without consuming the end of line; Readln consumes the rest of the line.
Multiple values on one line: Readln(A, B, C); (separated by spaces).
Robust input: read a string, then convert with TryStrToInt.
program Greeting;
{$mode objfpc}{$H+}
var
Name: string;
Age: Integer;
begin
Write('Your name: ');
Readln(Name);
Write('Your age: ');
Readln(Age); // run-time error 106 if the input is not a number
Writeln('Hello, ', Name, '! Next year you will be ', Age + 1, '.');
end.function ReadInteger(const Prompt: string): Integer;
var
S: string;
begin
repeat
Write(Prompt);
Readln(S);
until TryStrToInt(Trim(S), Result);
end;8.5 Standard files and EOF
Input and Output are predefined text files; ErrOutput (and StdErr in FPC) writes to standard error. Eof without arguments tests the standard input, which makes filters easy:
Run: linecount < data.txt.
program LineCount;
var
Line: string;
N: Integer = 0;
begin
while not Eof do
begin
Readln(Line);
Inc(N);
end;
Writeln(N, ' lines');
end.8.6 Command-line arguments
For option parsing, see TCustomApplication (FPC CustApp unit) or FindCmdLineSwitch in SysUtils.
var
I: Integer;
begin
Writeln('Program: ', ParamStr(0));
for I := 1 to ParamCount do
Writeln('Arg ', I, ': ', ParamStr(I));
end.