ZetCode

Modula-2 console output

last modified November 27, 2026 Modula-2

Up to this point the series has used the modules of Wirth's book: InOut for text and whole numbers and RealInOut for reals. From this article on, the library topics use the standard ISO library. This article explains the switch and covers console output with STextIO, SWholeIO and SRealIO.

Why the switch

Programming in Modula-2 defines a handful of library modules as examples, not as a standard, and every compiler of the 1980s shipped its own variant of them. Files, command-line arguments, the environment and error handling were never specified, so programs that used them were tied to one compiler. ISO 10514, published in 1996, fixed this with a layered library of channels. A channel is a source or destination of data: the terminal, a file, the program arguments. The same procedures read and write all of them, and every read reports a result.

The ISO library is larger than InOut, and the most common tasks have simple modules of their own. STextIO writes text, SWholeIO whole numbers and SRealIO reals, all on the default output channel; the S stands for simple. The examples are compiled with -fiso, which selects the ISO dialect: it enables the ISO additions to the language, and a plain import of Strings then means the ISO Strings module rather than the Logitech one used in the strings article.

The first ISO program

STextIO provides WriteString, WriteChar and WriteLn. Apart from the module name, the program looks like one written with InOut.

greeting.mod
MODULE greeting;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;

VAR
  i: CARDINAL;

BEGIN
  WriteString("Hello there!");
  WriteLn;
  FOR i := 1 TO 12 DO
    WriteChar('-')
  END;
  WriteLn
END greeting.

WriteString writes a string, WriteChar a single character, and WriteLn ends the line. The program is compiled with -fiso; the ISO modules also link without it, but the series uses the flag consistently from now on.

$ gm2 -fiso greeting.mod -o greeting
$ ./greeting
Hello there!
------------

Whole numbers

SWholeIO writes INTEGER values with WriteInt and CARDINAL values with WriteCard. The second parameter is the field width.

wholes.mod
MODULE wholes;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;

VAR
  n: INTEGER;
  c: CARDINAL;

BEGIN
  n := -273;
  c := 1024;
  WriteString("["); WriteInt(n, 0); WriteString("]"); WriteLn;
  WriteString("["); WriteInt(n, 8); WriteString("]"); WriteLn;
  WriteString("["); WriteCard(c, 8); WriteString("]"); WriteLn;
  WriteString("["); WriteCard(c, 2); WriteString("]"); WriteLn;
  WriteString("["); WriteInt(MIN(INTEGER), 0); WriteString("]"); WriteLn;
  WriteString("["); WriteCard(MAX(CARDINAL), 0); WriteString("]"); WriteLn
END wholes.

The number is right-aligned in a field of the given width. A width of 0 writes the number with no padding, and a number wider than its field is written in full: the width is a minimum, never a limit. The brackets show where each field starts and ends. A positive number is written without a plus sign.

$ gm2 -fiso wholes.mod -o wholes
$ ./wholes
[-273]
[    -273]
[    1024]
[1024]
[-2147483648]
[4294967295]

Columns

Because every number fills its field, a fixed width for each column lines the numbers up into a table.

powers.mod
MODULE powers;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  n: CARDINAL;

BEGIN
  WriteString("  n     n^2       n^3"); WriteLn;
  FOR n := 1 TO 12 DO
    WriteCard(n, 3);
    WriteCard(n * n, 8);
    WriteCard(n * n * n, 10);
    WriteLn
  END
END powers.

Each row writes three cardinals with widths 3, 8 and 10, so the last digits of each column sit under each other. The header is a plain string whose spacing matches the widths.

$ gm2 -fiso powers.mod -o powers
$ ./powers
  n     n^2       n^3
  1       1         1
  2       4         8
  3       9        27
  4      16        64
  5      25       125
  6      36       216
  7      49       343
  8      64       512
  9      81       729
 10     100      1000
 11     121      1331
 12     144      1728

Fixed-point reals

SRealIO.WriteFixed writes a real in fixed-point notation. Its parameters are the value, the number of places after the decimal point, and the field width.

fixed.mod
MODULE fixed;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;

VAR
  x: REAL;

BEGIN
  x := 1234.5678;
  WriteString("2 places:  "); WriteFixed(x, 2, 0); WriteLn;
  WriteString("4 places:  "); WriteFixed(x, 4, 0); WriteLn;
  WriteString("0 places:  "); WriteFixed(x, 0, 0); WriteLn;
  WriteString("-1 places: "); WriteFixed(x, -1, 0); WriteLn;
  WriteString("-2 places: "); WriteFixed(x, -2, 0); WriteLn;
  WriteString("width 12:  ["); WriteFixed(x, 2, 12); WriteString("]"); WriteLn;
  WriteString("small:     "); WriteFixed(0.004, 2, 0); WriteLn;
  WriteString("negative:  "); WriteFixed(-0.75, 1, 0); WriteLn
END fixed.

The value is rounded to the requested number of places. With 0 places the decimal point is still written, which marks the number as a real. A negative place count rounds to the left of the decimal point: -1 rounds to whole units and drops the point, -2 rounds to tens. 0.004 rounds to 0.00, and -0.75 rounds away from zero to -0.8. The place count is an INTEGER, unlike the width, which is a CARDINAL. InOut had nothing comparable; RealInOut.WriteReal always wrote six decimals.

$ gm2 -fiso fixed.mod -o fixed
$ ./fixed
2 places:  1234.57
4 places:  1234.5678
0 places:  1235.
-1 places: 1235
-2 places: 1230
width 12:  [     1234.57]
small:     0.00
negative:  -0.8

Scientific notation

Very large and very small values are written in scientific notation with WriteFloat. Its second parameter is the number of significant digits.

floats.mod
MODULE floats;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFloat, WriteEng;

VAR
  c, h: REAL;

BEGIN
  c := 299792458.0;
  h := 6.62607015E-34;
  WriteString("c, 3 digits:  "); WriteFloat(c, 3, 0); WriteLn;
  WriteString("c, 9 digits:  "); WriteFloat(c, 9, 0); WriteLn;
  WriteString("h, 4 digits:  "); WriteFloat(h, 4, 0); WriteLn;
  WriteString("1 digit:      "); WriteFloat(0.25, 1, 0); WriteLn;
  WriteString("width 12:     ["); WriteFloat(-c, 3, 12); WriteString("]"); WriteLn;
  WriteString("engineering:  "); WriteEng(c, 4, 0); WriteLn
END floats.

WriteFloat writes one digit before the decimal point and an exponent after E. Three significant digits round the speed of light to 3.00E+8, and nine digits show it exactly. WriteEng should write engineering notation, with an exponent that is a multiple of three (299.8E+6), but in gm2 15.2 it writes the same as WriteFloat.

$ gm2 -fiso floats.mod -o floats
$ ./floats
c, 3 digits:  3.00E+8
c, 9 digits:  2.99792458E+8
h, 4 digits:  6.626E-34
1 digit:      3E-1
width 12:     [    -3.00E+8]
engineering:  2.998E+8

Letting the library choose

WriteReal takes only a width. It writes the value in fixed-point notation if it fits into the field, and in scientific notation otherwise.

reals.mod
MODULE reals;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteReal;

PROCEDURE Show(x: REAL; width: CARDINAL);
BEGIN
  WriteString("["); WriteReal(x, width); WriteString("]"); WriteLn
END Show;

BEGIN
  Show(3.14159, 10);
  Show(3.14159, 4);
  Show(1.0E20, 10);
  Show(123456789.0, 8);
  Show(0.5, 0)
END reals.

The digits fill the field: 3.14159 in 10 characters gets trailing zeros, in 4 characters it is cut to 3.14. Values that do not fit switch to scientific notation. The last call shows a gm2 15.2 bug: with a width of 0 WriteReal writes nothing at all. When the format matters, WriteFixed and WriteFloat are the better choice.

$ gm2 -fiso reals.mod -o reals
$ ./reals
[3.14159000]
[3.14]
[1.0000E+20]
[1.235E+8]
[]

Two libraries, one name

InOut and STextIO both export WriteString and WriteLn. A program cannot import the same name from two modules with FROM.

clash.mod
MODULE clash;
FROM InOut IMPORT WriteString, WriteLn;
FROM STextIO IMPORT WriteString, WriteLn;

BEGIN
  WriteString("Which one?");
  WriteLn
END clash.

The compiler would not know which WriteString the body means, so it rejects the second import.

$ gm2 -fiso clash.mod -o clash
clash.mod:5:1: error: In program module ‘clash’: name clash when trying to import (WriteString)
    5 | BEGIN
      | ^~~~~
clash.mod:5:1: error: name clash when trying to import (WriteLn)

InOut next to ISO

A plain IMPORT brings in the module names instead, and every use is qualified with the module. This lets the two libraries meet in one program.

compare.mod
MODULE compare;
IMPORT InOut, RealInOut, STextIO, SWholeIO, SRealIO;

VAR
  n: INTEGER;
  x: REAL;

BEGIN
  n := -42;
  x := 2.0 / 3.0;
  InOut.WriteString("InOut:   ");
  InOut.WriteInt(n, 6);
  RealInOut.WriteReal(x, 12);
  InOut.WriteLn;
  STextIO.WriteString("ISO:     ");
  SWholeIO.WriteInt(n, 6);
  SRealIO.WriteFixed(x, 6, 12);
  STextIO.WriteLn
END compare.

The same integer and real are written once with the PIM modules and once with the ISO modules. InOut.WriteInt and SWholeIO.WriteInt agree. RealInOut.WriteReal fixes the decimals at six; SRealIO.WriteFixed takes them as a parameter. The series does not mix the libraries in one program; the example only shows how the procedures correspond.

$ gm2 -fiso compare.mod -o compare
$ ./compare
InOut:      -42    0.666667
ISO:        -42    0.666667

Long types

The simple modules have long variants: SLongWholeIO for LONGINT and SLongIO for LONGREAL. Their procedures have the same names as in SWholeIO and SRealIO, so the program imports all four modules qualified.

longs.mod
MODULE longs;
FROM STextIO IMPORT WriteString, WriteLn;
IMPORT SWholeIO, SLongWholeIO, SRealIO, SLongIO;

VAR
  big: LONGINT;
  third: LONGREAL;

BEGIN
  big := MAX(LONGINT);
  WriteString("MAX(INTEGER): "); SWholeIO.WriteInt(MAX(INTEGER), 0); WriteLn;
  WriteString("MAX(LONGINT): "); SLongWholeIO.WriteInt(big, 0); WriteLn;
  third := 1.0 / 3.0;
  WriteString("REAL:     "); SRealIO.WriteFixed(1.0 / 3.0, 18, 0); WriteLn;
  WriteString("LONGREAL: "); SLongIO.WriteFixed(third, 18, 0); WriteLn
END longs.

LONGINT has 64 bits, and SLongWholeIO.WriteInt writes its largest value. A REAL holds about 16 significant digits, so one third written to 18 places ends in noise; LONGREAL is 80-bit extended precision on x86-64 and keeps all 18 places.

$ gm2 -fiso longs.mod -o longs
$ ./longs
MAX(INTEGER): 2147483647
MAX(LONGINT): 9223372036854775807
REAL:     0.333333333333333315
LONGREAL: 0.333333333333333333

Numbers in strings

Sometimes a number is needed as text rather than on the screen, for example to measure it or to join it with other text. WholeStr and RealStr convert numbers to strings with the same rules as the output procedures.

tostr.mod
MODULE tostr;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM WholeStr IMPORT IntToStr;
FROM RealStr IMPORT RealToFixed;
FROM Strings IMPORT Length, Concat;

VAR
  num, text: ARRAY [0..31] OF CHAR;

BEGIN
  IntToStr(-1250, num);
  WriteString("["); WriteString(num); WriteString("] has ");
  WriteCard(Length(num), 0); WriteString(" characters"); WriteLn;
  RealToFixed(9.80665, 2, num);
  Concat("g = ", num, text);
  WriteString(text); WriteLn
END tostr.

IntToStr stores -1250 as the five characters -1250, and Length from the ISO Strings module counts them. RealToFixed takes the same place count as WriteFixed, and Concat joins two strings into a third.

$ gm2 -fiso tostr.mod -o tostr
$ ./tostr
[-1250] has 5 characters
g = 9.81

Left-aligned columns

Numbers are right-aligned in their fields, but there is no width parameter for strings. A short procedure pads a string with spaces to a given width, which gives left-aligned text columns.

padding.mod
MODULE padding;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Strings IMPORT Length;

PROCEDURE WriteLeft(s: ARRAY OF CHAR; width: CARDINAL);
VAR
  i: CARDINAL;
BEGIN
  WriteString(s);
  FOR i := Length(s) + 1 TO width DO
    WriteChar(' ')
  END
END WriteLeft;

PROCEDURE Item(name: ARRAY OF CHAR; price: REAL);
BEGIN
  WriteLeft(name, 12);
  WriteFixed(price, 2, 8);
  WriteLn
END Item;

BEGIN
  Item("bread", 2.4);
  Item("cheese", 7.95);
  Item("apples", 3.0);
  Item("olive oil", 12.5);
  WriteLeft("total", 12);
  WriteFixed(2.4 + 7.95 + 3.0 + 12.5, 2, 8);
  WriteLn
END padding.

WriteLeft writes the string and then one space for each position between its length and the width. If the string is longer than the width, the FOR loop does not run, and the string is written in full. Item combines a left-aligned name with a right-aligned price, the usual layout of a receipt.

$ gm2 -fiso padding.mod -o padding
$ ./padding
bread           2.40
cheese          7.95
apples          3.00
olive oil      12.50
total          25.85

Standard error

Error messages belong on standard error, so that they stay visible when the normal output is redirected to a file. The simple modules write only to the default output channel. StdChans.StdErrChan returns the channel of standard error, and TextIO writes to any channel given as the first parameter.

mixed.mod
MODULE mixed;
FROM STextIO IMPORT WriteString, WriteLn;
IMPORT TextIO, StdChans;

VAR
  err: StdChans.ChanId;

BEGIN
  err := StdChans.StdErrChan();
  TextIO.WriteString(err, "warning: no settings file, using defaults");
  TextIO.WriteLn(err);
  WriteString("width = 80");
  WriteLn
END mixed.

The warning goes to standard error and the result to standard output. Redirecting one of them separates the two streams correctly. On a terminal, where both meet, the line break of the warning comes too late: gm2 holds back the end of each line on a channel until the next output on that channel, or the end of the program.

$ gm2 -fiso mixed.mod -o mixed
$ ./mixed
warning: no settings file, using defaultswidth = 80
$ ./mixed 2>/dev/null
width = 80
$ ./mixed >/dev/null
warning: no settings file, using defaults

Flushing a channel

IOChan.Flush writes everything that is pending on a channel. Calling it after the warning puts the line break where it belongs.

errors.mod
MODULE errors;
FROM STextIO IMPORT WriteString, WriteLn;
IMPORT TextIO, StdChans, IOChan;

VAR
  err: StdChans.ChanId;

BEGIN
  err := StdChans.StdErrChan();
  TextIO.WriteString(err, "warning: no settings file, using defaults");
  TextIO.WriteLn(err);
  IOChan.Flush(err);
  WriteString("width = 80");
  WriteLn
END errors.

Flushing the error channel after each message is enough when standard output and standard error share a terminal. A program that writes only to standard output never needs it, because all pending output is written when the program ends.

$ gm2 -fiso errors.mod -o errors
$ ./errors
warning: no settings file, using defaults
width = 80

A savings table

The last program puts the output procedures together. It deposits the same amount at the start of every year and prints the interest and the balance of each year as a table.

savings.mod
MODULE savings;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;

CONST
  Deposit = 1200.0;
  Rate = 3.5;
  Years = 10;

VAR
  year, i: CARDINAL;
  balance, interest, total: REAL;

BEGIN
  WriteString("Yearly deposit "); WriteFixed(Deposit, 2, 0);
  WriteString(", interest "); WriteFixed(Rate, 1, 0); WriteChar('%'); WriteLn;
  WriteLn;
  WriteString("Year   Interest     Balance"); WriteLn;
  FOR i := 1 TO 27 DO WriteChar('-') END;
  WriteLn;
  balance := 0.0;
  total := 0.0;
  FOR year := 1 TO Years DO
    balance := balance + Deposit;
    interest := balance * Rate / 100.0;
    balance := balance + interest;
    total := total + interest;
    WriteCard(year, 4);
    WriteFixed(interest, 2, 11);
    WriteFixed(balance, 2, 12);
    WriteLn
  END;
  FOR i := 1 TO 27 DO WriteChar('-') END;
  WriteLn;
  WriteString("    ");
  WriteFixed(total, 2, 11);
  WriteFixed(balance, 2, 12);
  WriteLn
END savings.

Each year the deposit is added, and the interest is computed on the new balance. WriteCard writes the year in a field of 4, and two WriteFixed calls write the money with 2 places in fields of 11 and 12, matching the header line. The total of the interest is accumulated in the loop and written under its column; the % sign is a character of its own and is written with WriteChar.

$ gm2 -fiso savings.mod -o savings
$ ./savings
Yearly deposit 1200.00, interest 3.5%

Year   Interest     Balance
---------------------------
   1      42.00     1242.00
   2      85.47     2527.47
   3     130.46     3857.93
   4     177.03     5234.96
   5     225.22     6660.18
   6     275.11     8135.29
   7     326.74     9662.02
   8     380.17    11242.19
   9     435.48    12877.67
  10     492.72    14570.39
---------------------------
        2570.39    14570.39

Source

The GNU Modula-2 manual

The ISO libraries in GNU Modula-2

In this article we have switched from the PIM modules to the ISO library and written text, whole numbers and reals with STextIO, SWholeIO, SRealIO and their long variants. We have used field widths, fixed-point and scientific notation, converted numbers to strings, padded columns, written to standard error, and printed a savings table. The reading input article reads from the same default channels, and files writes with TextIO to channels opened on files.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.