Learn/Zig/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

Zig, lesson 3

Reading input and arithmetic

Your exercises receive their input on standard input (stdin), one line at a time. Reading in Zig mirrors writing: you set up a buffered reader once, then take lines from it.

Taking a line

in.takeDelimiter('\n') reads up to the next line break and gives you the text without it. Its result type is !?[]u8, which packs two ideas:

  • the ! means it can fail (for example if the line is longer than the buffer), so you try it;
  • the ? means it is optional: it returns null when the input has run out.

orelse supplies a value for the case:

2 exercises to try what you just read.

Exercise 1

Pizza party

Press Ctrl Enter or Check to test your code.

Exercise 2

Celsius to Fahrenheit

Press Ctrl Enter or Check to test your code.

null

The slice you get points into in_buf. The next read may overwrite it, so finish with one line (for example, turn it into a number) before taking the next.

Input from other systems sometimes ends lines with \r\n or carries stray spaces, so trim it:

Text to numbers

You tell parseInt which integer type you want. Both return an error if the text is not a valid number, and try passes that error up out of main, which stops the program with a message.

Arithmetic

+, - and * work as usual. Division is where Zig asks you to be specific:

ExpressionMeaning
a / bdivision; for integers, allowed directly only on unsigned types
a % bremainder; same rule
@divTrunc(a, b)signed integer division rounding toward zero: -7 / 2 gives -3
@divFloor(a, b)signed integer division rounding down: gives -4
@rem(a, b), @mod(a, b)the matching remainders for signed integers

For signed integers, "round toward zero" and "round down" give different answers for negative numbers, so Zig refuses to guess and makes you pick. When your values can't be negative, use an unsigned type like u64 and plain / and % work.

Mixing integers and floats

Zig never converts between number types silently. To use an integer in a float calculation, convert it with @floatFromInt, and go back with @intFromFloat:

@as(f64, ...) states the type you want, so @floatFromInt knows what to produce. Number literals like 9 or 32 adapt automatically, so celsius * 9 / 5 + 32 just works when celsius is an f64. Print floats with {d} too.

Further reading

  • Zig Language Reference: Optionals
  • Zig Language Reference: Operators
  • Standard library: std.fmt.parseInt
  • Standard library: std.Io.Reader

A group shares some pizza slices equally. Every person gets the same whole number of slices, and the rest are left over.

Input: two lines. The first is the number of slices (0 or more), the second the number of people (1 or more).

Output: two lines:

That sample is for the input:

The starter already reads both numbers as u64, so / and % are allowed.

Read a temperature in degrees Celsius and print it in Fahrenheit, using F = C * 9 / 5 + 32.

Input: one line with a number, which may have a decimal part (36.6) or not (100).

Output: just the Fahrenheit value. Any normal float form is accepted, so 212.0 and 212 both count for 100 °C.

prints

var in_buf: [1024]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(init.io, &in_buf);
const in = &stdin_reader.interface;
const line = (try in.takeDelimiter('\n')) orelse "";
const text = std.mem.trim(u8, line, " \t\r");
const age = try std.fmt.parseInt(i64, text, 10);       // base 10
const height = try std.fmt.parseFloat(f64, "1.75");
const people: i64 = 4;
const bill: f64 = 50.0;
const share = bill / @as(f64, @floatFromInt(people));   // 12.5
Each person gets 3 slices.
Leftover: 2
14
4
37
98.6