# A Word-Count Program

### A Word-Count Program

A useful program reads text and counts something.

This program counts bytes from standard input:

```zig
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:

```sh
zig run main.zig
```

Type some text, then end the input.

On Unix-like systems, press `Ctrl-D`.

On Windows, press `Ctrl-Z` and then Enter.

Example:

```text
hello
```

The output is:

```text
6
```

The count is 6 because the input contains five letters and one newline.

The variable:

```zig
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:

```zig
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:

```zig
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:

```zig
|_|
```

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:

```zig
return err;
```

Now count lines instead of bytes:

```zig
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:

```zig
'\n'
```

is the newline byte.

This is still a small program, but it already has the shape of many real programs:

```text
read input
process bytes
print result
handle errors
```

There is no hidden exception mechanism. The possible error is visible in the type of `main`:

```zig
pub fn main() !void
```

The `!` 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:

```sh
zig run main.zig < input.txt
```

