ZetCode

Modula-2 reading input

last modified November 27, 2026 Modula-2

The ISO library reads from the default input channel with the same simple modules that write to the default output channel: STextIO for text, SWholeIO for whole numbers and SRealIO for reals. Every read sets a read result, which tells the program whether the read succeeded, stopped at the end of a line, or reached the end of the input. This article reads names, lines, characters, words and numbers, and checks the input along the way.

Reading a line

STextIO.ReadString reads the characters of the current line into a character array. The program asks for a name and greets the user.

name.mod
MODULE name;
FROM STextIO IMPORT WriteString, WriteLn, ReadString, SkipLine;

VAR
  name: ARRAY [0..39] OF CHAR;

BEGIN
  WriteString("Enter your name: ");
  ReadString(name);
  SkipLine;
  WriteString("Nice to meet you, ");
  WriteString(name);
  WriteString("!");
  WriteLn
END name.

ReadString stops at the end of the line, or earlier if the array is full, and terminates the string with 0C when there is room. It does not remove the line mark, the end-of-line character that the Enter key produced. SkipLine removes the rest of the line together with its line mark, so the next read starts on a new line. A prompt written with WriteString appears before the program waits for input, without an explicit flush.

$ gm2 -fiso name.mod -o name
$ ./name
Enter your name: Lucia
Nice to meet you, Lucia!

The line mark

The next program forgets SkipLine and reads two names in a row.

twonames.mod
MODULE twonames;
FROM STextIO IMPORT WriteString, WriteLn, ReadString;

VAR
  first, last: ARRAY [0..39] OF CHAR;

BEGIN
  WriteString("First name: ");
  ReadString(first);
  WriteString("Last name: ");
  ReadString(last);
  WriteString("[");
  WriteString(first);
  WriteString("] [");
  WriteString(last);
  WriteString("]");
  WriteLn
END twonames.

The first ReadString stops before the line mark, and the second one finds it at once. It reads nothing, returns an empty string, and the program finishes without waiting for the last name. ISO reads never cross a line mark on their own; the program decides when a line is done by calling SkipLine.

$ gm2 -fiso twonames.mod -o twonames
$ ./twonames
First name: Lucia
Last name: [Lucia] []

Reading every line

SIOResult.ReadResult returns the result of the last read on the default input channel. Its type ReadResults has the values notKnown, allRight, outOfRange, wrongFormat, endOfLine and endOfInput. A loop that reads until endOfInput processes the whole input.

numbered.mod
MODULE numbered;
FROM STextIO IMPORT WriteString, WriteLn, ReadString, SkipLine;
FROM SWholeIO IMPORT WriteCard;
FROM SIOResult IMPORT ReadResult, ReadResults;

VAR
  line: ARRAY [0..255] OF CHAR;
  count: CARDINAL;

BEGIN
  count := 0;
  ReadString(line);
  WHILE ReadResult() # endOfInput DO
    INC(count);
    WriteCard(count, 3);
    WriteString("  ");
    WriteString(line);
    WriteLn;
    SkipLine;
    ReadString(line)
  END
END numbered.

The program numbers the lines of its input. It reads a line before the loop and another one at the end of each pass, so the test in the WHILE always looks at the latest read. The input comes from the file note.txt through a shell redirection; at the terminal, Ctrl+D on an empty line ends the input.

$ gm2 -fiso numbered.mod -o numbered
$ ./numbered < note.txt
  1  Modula-2 came out of the Lilith project.
  2  The workstation and its operating system
  3  were written in the new language.

A missing line mark

Most text files end with a line mark, but not all of them do. The printf command below sends two lines, the second without a line mark, to the numbering program.

The second line is lost. In gm2 15.2, a ReadString that stops at the end of the input reports endOfInput even when it has read characters, and the loop ends before it processes them. In the same way, a read that stops at a line mark reports endOfLine rather than allRight. The ISO standard reserves both results for reads that find no data, so a portable loop must not rely on this either way.

$ printf 'one\ntwo' | ./numbered
  1  one

Counting every line

The safe test for the end of the input is endOfInput together with an empty string. A LOOP with EXIT puts the test right after the read.

lastline.mod
MODULE lastline;
FROM STextIO IMPORT WriteString, WriteLn, ReadString, SkipLine;
FROM SWholeIO IMPORT WriteCard;
FROM SIOResult IMPORT ReadResult, ReadResults;
FROM Strings IMPORT Length;

VAR
  line: ARRAY [0..255] OF CHAR;
  count, chars: CARDINAL;

BEGIN
  count := 0;
  chars := 0;
  LOOP
    ReadString(line);
    IF (ReadResult() = endOfInput) AND (Length(line) = 0) THEN
      EXIT
    END;
    INC(count);
    INC(chars, Length(line));
    SkipLine
  END;
  WriteCard(count, 0); WriteString(" lines, ");
  WriteCard(chars, 0); WriteString(" characters");
  WriteLn
END lastline.

The loop leaves only when the read reached the end of the input and found nothing. A last line without a line mark is counted like any other, and an empty line in the middle of the input is counted too, because there the result is endOfLine. Length comes from the ISO Strings module.

$ gm2 -fiso lastline.mod -o lastline
$ ./lastline < note.txt
3 lines, 113 characters
$ printf 'one\ntwo' | ./lastline
2 lines, 6 characters

Long lines

A line longer than the array is not an error. ReadString reads as much as fits and leaves the rest for the next read. The next program reads into an array of eight characters and shows each piece.

pieces.mod
MODULE pieces;
FROM STextIO IMPORT WriteString, WriteLn, ReadString, SkipLine;
FROM SIOResult IMPORT ReadResult, ReadResults;

VAR
  part: ARRAY [0..7] OF CHAR;
  res: ReadResults;

BEGIN
  LOOP
    ReadString(part);
    res := ReadResult();
    IF part[0] # 0C THEN
      WriteString("[");
      WriteString(part);
      WriteString("]")
    END;
    IF res = endOfLine THEN
      WriteLn;
      SkipLine
    ELSIF res = endOfInput THEN
      EXIT
    END
  END
END pieces.

The pieces come out in order, and the line ends where the result is endOfLine. A program that wants only the beginning of each line calls SkipLine after the first read and discards the rest. Here an empty line gives an empty piece and is written as an empty line.

$ gm2 -fiso pieces.mod -o pieces
$ echo 'A line that is longer than eight characters' | ./pieces
[A line t][hat is l][onger th][an eight][ charact][ers]
$ printf 'short\n\n12345678\n' | ./pieces
[short]

[12345678]

Characters

ReadChar reads a single character. At a line mark it reports endOfLine and leaves the mark in place, so a character loop handles line ends the same way as a line loop. The program copies its input and squeezes runs of spaces into one.

squeeze.mod
MODULE squeeze;
FROM STextIO IMPORT WriteChar, WriteLn, ReadChar, SkipLine;
FROM SIOResult IMPORT ReadResult, ReadResults;

VAR
  ch: CHAR;
  res: ReadResults;
  space: BOOLEAN;

BEGIN
  space := FALSE;
  LOOP
    ReadChar(ch);
    res := ReadResult();
    IF res = endOfInput THEN
      EXIT
    ELSIF res = endOfLine THEN
      WriteLn;
      SkipLine;
      space := FALSE
    ELSIF ch = ' ' THEN
      IF NOT space THEN WriteChar(' ') END;
      space := TRUE
    ELSE
      WriteChar(ch);
      space := FALSE
    END
  END
END squeeze.

space remembers whether the last character written was a space; further spaces are dropped until another character comes. At the end of a line the program writes a line mark of its own, skips the one in the input and starts afresh. The character handling article shows more character loops, written with InOut.Read.

$ gm2 -fiso squeeze.mod -o squeeze
$ cat spaced.txt
In   the    beginning   there
was   a  lot    of     space.
$ ./squeeze < spaced.txt
In the beginning there
was a lot of space.

Words

ReadToken skips spaces and reads the characters up to the next space or line mark: one word. It reports endOfLine at the end of a line, like the other reads.

words.mod
MODULE words;
FROM STextIO IMPORT WriteString, WriteLn, ReadToken, SkipLine;
FROM SWholeIO IMPORT WriteCard;
FROM SIOResult IMPORT ReadResult, ReadResults;
FROM Strings IMPORT Length, Assign;

VAR
  word, longest: ARRAY [0..63] OF CHAR;
  res: ReadResults;
  count: CARDINAL;

BEGIN
  count := 0;
  longest := "";
  LOOP
    ReadToken(word);
    res := ReadResult();
    IF Length(word) > 0 THEN
      INC(count);
      IF Length(word) > Length(longest) THEN
        Assign(word, longest)
      END
    END;
    IF res = endOfInput THEN
      EXIT
    ELSIF res = endOfLine THEN
      SkipLine
    END
  END;
  WriteCard(count, 0); WriteString(" words, the longest is ");
  WriteString(longest);
  WriteLn
END words.

The loop counts the words and keeps the longest one with Assign from the ISO Strings module. A read can return a word and endOfLine at the same time, so the word is counted first and the result checked afterwards. An empty line and the read at the end of the input give an empty string, which is not counted.

$ gm2 -fiso words.mod -o words
$ ./words < note.txt
19 words, the longest is workstation

Reading a real

SRealIO.ReadReal reads a real number. When the input is not a number, the read result is wrongFormat.

fever.mod
MODULE fever;
FROM STextIO IMPORT WriteString, WriteLn, SkipLine;
FROM SRealIO IMPORT ReadReal, WriteFixed;
FROM SIOResult IMPORT ReadResult, ReadResults;

VAR
  t: REAL;

BEGIN
  WriteString("Body temperature in Celsius: ");
  ReadReal(t);
  IF ReadResult() = allRight THEN
    SkipLine;
    WriteFixed(t, 1, 0);
    WriteString(" C is ");
    WriteFixed(t * 9.0 / 5.0 + 32.0, 1, 0);
    WriteString(" F");
    IF t >= 38.0 THEN WriteString(", a fever") END;
    WriteLn
  ELSE
    WriteString("not a number");
    WriteLn
  END
END fever.

The program converts a body temperature from Celsius to Fahrenheit and only uses the value when the result is allRight. The second run types a word, and the program says so instead of computing with an undefined value.

$ gm2 -fiso fever.mod -o fever
$ ./fever
Body temperature in Celsius: 38.4
38.4 C is 101.1 F, a fever
$ ./fever
Body temperature in Celsius: high
not a number

Reading a whole number

SWholeIO.ReadInt should work the same way for whole numbers. The next program reads a number and prints the value and the read result.

readint.mod
MODULE readint;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT ReadInt, WriteInt;
FROM SIOResult IMPORT ReadResult, ReadResults;

VAR
  n: INTEGER;
  res: ReadResults;

BEGIN
  n := 0;
  WriteString("Enter a whole number: ");
  ReadInt(n);
  res := ReadResult();
  WriteString("n = "); WriteInt(n, 0); WriteString(", result ");
  CASE res OF
    allRight: WriteString("allRight")
  | wrongFormat: WriteString("wrongFormat")
  | outOfRange: WriteString("outOfRange")
  | endOfLine: WriteString("endOfLine")
  | endOfInput: WriteString("endOfInput")
  ELSE
    WriteString("notKnown")
  END;
  WriteLn
END readint.

In gm2 15.2 the results are unreliable. A correct number followed by the line mark gives endOfLine, the word abc gives allRight without assigning a value, and a number that is too large for INTEGER wraps around instead of reporting outOfRange. WholeStr.StrToInt, which converts a string, is not much better: it accepts 8x as 8 and wraps on overflow too. For whole numbers typed by a person, the program has to check the digits itself.

$ gm2 -fiso readint.mod -o readint
$ ./readint
Enter a whole number: 42
n = 42, result endOfLine
$ ./readint
Enter a whole number: abc
n = 0, result allRight
$ ./readint
Enter a whole number: 99999999999
n = 1215752191, result endOfLine

Checking a number

The checked way reads the whole line with ReadString and converts it with a procedure that accepts only a valid whole number.

checked.mod
MODULE checked;
FROM STextIO IMPORT WriteString, WriteLn, ReadString, SkipLine;
FROM SWholeIO IMPORT WriteInt;

VAR
  line: ARRAY [0..79] OF CHAR;
  age: INTEGER;

PROCEDURE ToInt(s: ARRAY OF CHAR; VAR n: INTEGER): BOOLEAN;
VAR
  i, d: CARDINAL;
  negative: BOOLEAN;
BEGIN
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] = ' ') DO INC(i) END;
  negative := (i <= HIGH(s)) AND (s[i] = '-');
  IF (i <= HIGH(s)) AND ((s[i] = '-') OR (s[i] = '+')) THEN INC(i) END;
  IF (i > HIGH(s)) OR (s[i] < '0') OR (s[i] > '9') THEN RETURN FALSE END;
  n := 0;
  WHILE (i <= HIGH(s)) AND (s[i] >= '0') AND (s[i] <= '9') DO
    d := ORD(s[i]) - ORD('0');
    IF n > (MAX(INTEGER) - INTEGER(d)) DIV 10 THEN RETURN FALSE END;
    n := n * 10 + INTEGER(d);
    INC(i)
  END;
  WHILE (i <= HIGH(s)) AND (s[i] = ' ') DO INC(i) END;
  IF negative THEN n := -n END;
  RETURN (i > HIGH(s)) OR (s[i] = 0C)
END ToInt;

BEGIN
  LOOP
    WriteString("Enter your age: ");
    ReadString(line);
    SkipLine;
    IF ToInt(line, age) AND (age >= 0) AND (age <= 150) THEN EXIT END;
    WriteString("Please enter a whole number from 0 to 150."); WriteLn
  END;
  WriteString("In ten years you will be "); WriteInt(age + 10, 0); WriteLn
END checked.

ToInt skips leading spaces, accepts a sign, and requires at least one digit. Before each step it checks that n * 10 + d stays within MAX(INTEGER), which catches overflow before it happens. After the digits only spaces may follow. The function returns FALSE for anything else, and the main loop asks again until the age is a number in a sensible range.

$ gm2 -fiso checked.mod -o checked
$ ./checked
Enter your age: abc
Please enter a whole number from 0 to 150.
Enter your age: 12x
Please enter a whole number from 0 to 150.
Enter your age: 99999999999
Please enter a whole number from 0 to 150.
Enter your age: -3
Please enter a whole number from 0 to 150.
Enter your age: 37
In ten years you will be 47

Summing numbers

ToInt is useful in more than one program, so it moves into a module of its own. The definition module exports the procedure.

Numbers.def
DEFINITION MODULE Numbers;

PROCEDURE ToInt(s: ARRAY OF CHAR; VAR n: INTEGER): BOOLEAN;

END Numbers.

The implementation module holds the procedure from the previous program unchanged.

Numbers.mod
IMPLEMENTATION MODULE Numbers;

PROCEDURE ToInt(s: ARRAY OF CHAR; VAR n: INTEGER): BOOLEAN;
VAR
  i, d: CARDINAL;
  negative: BOOLEAN;
BEGIN
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] = ' ') DO INC(i) END;
  negative := (i <= HIGH(s)) AND (s[i] = '-');
  IF (i <= HIGH(s)) AND ((s[i] = '-') OR (s[i] = '+')) THEN INC(i) END;
  IF (i > HIGH(s)) OR (s[i] < '0') OR (s[i] > '9') THEN RETURN FALSE END;
  n := 0;
  WHILE (i <= HIGH(s)) AND (s[i] >= '0') AND (s[i] <= '9') DO
    d := ORD(s[i]) - ORD('0');
    IF n > (MAX(INTEGER) - INTEGER(d)) DIV 10 THEN RETURN FALSE END;
    n := n * 10 + INTEGER(d);
    INC(i)
  END;
  WHILE (i <= HIGH(s)) AND (s[i] = ' ') DO INC(i) END;
  IF negative THEN n := -n END;
  RETURN (i > HIGH(s)) OR (s[i] = 0C)
END ToInt;

END Numbers.

The program reads every word of its input with ReadToken and converts it with ToInt.

total.mod
MODULE total;
FROM STextIO IMPORT WriteString, WriteLn, ReadToken, SkipLine;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM SRealIO IMPORT WriteFixed;
FROM SIOResult IMPORT ReadResult, ReadResults;
FROM Numbers IMPORT ToInt;

VAR
  token: ARRAY [0..31] OF CHAR;
  res: ReadResults;
  n, sum, lowest, highest: INTEGER;
  count: CARDINAL;

BEGIN
  count := 0; sum := 0;
  lowest := MAX(INTEGER); highest := MIN(INTEGER);
  LOOP
    ReadToken(token);
    res := ReadResult();
    IF token[0] = 0C THEN
      (* an empty line or the end of input *)
    ELSIF ToInt(token, n) THEN
      INC(count);
      INC(sum, n);
      IF n < lowest THEN lowest := n END;
      IF n > highest THEN highest := n END
    ELSE
      WriteString("skipping "); WriteString(token); WriteLn
    END;
    IF res = endOfInput THEN EXIT
    ELSIF res = endOfLine THEN SkipLine
    END
  END;
  WriteString("count:   "); WriteCard(count, 0); WriteLn;
  IF count > 0 THEN
    WriteString("sum:     "); WriteInt(sum, 0); WriteLn;
    WriteString("lowest:  "); WriteInt(lowest, 0); WriteLn;
    WriteString("highest: "); WriteInt(highest, 0); WriteLn;
    WriteString("mean:    ");
    WriteFixed(FLOAT(sum) / FLOAT(count), 2, 0); WriteLn
  END
END total.

Valid numbers are added up, and the lowest and highest are kept; the starting values MAX(INTEGER) and MIN(INTEGER) make sure that the first number replaces both. Words that are not whole numbers, such as x5 and 3.5, are reported and skipped. The empty line in the input gives an empty token, which is ignored. Numbers is compiled separately with -c and linked to the program, as in the modules article.

$ cat numbers.txt
12 7 -3
40 x5 8

15 3.5 21
$ gm2 -fiso -c Numbers.mod
$ gm2 -fiso total.mod Numbers.o -o total
$ ./total < numbers.txt
skipping x5
skipping 3.5
count:   7
sum:     100
lowest:  -3
highest: 40
mean:    14.29

Source

The GNU Modula-2 manual

The ISO libraries in GNU Modula-2

In this article we have read lines, characters, words and numbers from the default input channel, used the read result to find line ends and the end of the input, handled long lines and a missing last line mark, and checked whole numbers with a conversion procedure of our own. The console output article covers the writing side, and the files article reads and writes files with the same procedures on channels of their own.

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.