Library reference

Use a fallback for invalid input

Try reading a whole number from a short piece of text. Here the form uses zero when someone types a word instead of a number.

std.fmt.parseInt

Simple example

Read the number in this text.

Start"3"
Result3
lesson.zig
const std = @import("std");

pub fn main() !void {
    const number = std.fmt.parseInt(i64, "3", 10) catch 0;
    std.debug.print("{any}\n", .{number});
}
Output
3
Advertisements

Everyday examples

A club form expects a number of guests. Someone enters none. How many extra seats does it reserve?

Start"none"
Result0
lesson.zig
const std = @import("std");

pub fn main() !void {
    const number = std.fmt.parseInt(i64, "none", 10) catch 0;
    std.debug.print("{any}\n", .{number});
}
Output
0

The parcel desk receives the package count as text. Read the count for the loading slip.

Start"12"
Result12
lesson.zig
const std = @import("std");

pub fn main() !void {
    const number = std.fmt.parseInt(i64, "12", 10) catch 0;
    std.debug.print("{any}\n", .{number});
}
Output
12

A learner enters two dashes for the number of extra notebooks. What default quantity goes on the order?

Start"--"
Result0
lesson.zig
const std = @import("std");

pub fn main() !void {
    const number = std.fmt.parseInt(i64, "--", 10) catch 0;
    std.debug.print("{any}\n", .{number});
}
Output
0
Run the example
Terminal
zig run lesson.zig
Official documentation