A useful program reads text and counts something.
This program counts bytes from standard input:
const std = @import("std");
pub fn main() !void {
var count: usize = 0;
const stdin = std.io.getStdIn().reader();
while (stdin.readByte()) |_| {
count += 1;
} else |err| {
if (err != error.EndOfStream) {
return err;
}
}
std.debug.print("{d}\n", .{count});
}Run it:
zig run main.zigType some text, then end the input.
On Unix-like systems, press Ctrl-D.
On Windows, press Ctrl-Z and then Enter.
Example:
helloThe output is:
6The count is 6 because the input contains five letters and one newline.
The variable:
var count: usize = 0;stores the number of bytes read.
usize is an unsigned integer type large enough to hold the size of an object in memory. It is commonly used for counts, lengths, and indexes.
The line:
const stdin = std.io.getStdIn().reader();gets a reader for standard input.
A reader is an object that knows how to read bytes.
The loop:
while (stdin.readByte()) |_| {
count += 1;
} else |err| {
if (err != error.EndOfStream) {
return err;
}
}calls readByte() repeatedly.
If one byte is read, the loop body runs.
The byte itself is ignored:
|_|Only the count matters.
When input ends, readByte() returns error.EndOfStream.
That error is not a failure for this program. It means there are no more bytes to read.
Any other error is returned:
return err;Now count lines instead of bytes:
const std = @import("std");
pub fn main() !void {
var lines: usize = 0;
const stdin = std.io.getStdIn().reader();
while (stdin.readByte()) |byte| {
if (byte == '\n') {
lines += 1;
}
} else |err| {
if (err != error.EndOfStream) {
return err;
}
}
std.debug.print("{d}\n", .{lines});
}The character literal:
'\n'is the newline byte.
This is still a small program, but it already has the shape of many real programs:
read input
process bytes
print result
handle errorsThere is no hidden exception mechanism. The possible error is visible in the type of main:
pub fn main() !voidThe ! says that the function may fail.
Exercise 1-25. Change the byte-count program to count only the byte a.
Exercise 1-26. Change the line-count program to count spaces.
Exercise 1-27. Print both the byte count and the line count.
Exercise 1-28. Run the program with input from a file:
zig run main.zig < input.txt