Parse an integer from zero terminated string

Hi all, I want learn my first bits of zig by writing some simple programs that read the command line arguments and I can’t figure out how to read some ints.

Following this post Read command line arguments I tried using std.os.argv which seems the less verbose one and:

    const n: i32 = try std.fmt.parseInt(i32, std.os.argv[1], 10);

But parseInt is expecting a []const u8 and std.os.arvg.[1] has type [*:0]u8 so I get an error. Is there a way to parse some value of the latter type directly? Or do I have to instantiate an array? How is that done? Or there is another way suggested for doing this?

You can use the std.mem.sliceTo function to convert an argv value.

For instance,

const std = @import("std");

pub fn main() !void {
    const data = std.os.argv[1];
    std.debug.print("{}\n", .{try std.fmt.parseInt(i32, std.mem.sliceTo(data, 0), 0)}); // 4
}

see also: API reference page

4 Likes

There’s also std.mem.span which is like a specialized version of sliceTo. So the call would be std.mem.span(std.os.argv[1]). I hadn’t run into this situation with args since I’m used to using std.process.args which returns an iterator over the args as strings:

var args_iter = std.process.args();
_ = args_iter.next(); // skip program name
const second_arg = args_iter.next() orelse print_usage_and_exit();
const n: i32 = try std.fmt.parseInt(i32, second_arg, 10);
9 Likes

FYI:

std.os.argv is not supported on Windos OS.
In Windows, It must use std.process.args function.

1 Like

You mean argsWithAllocator or argsAlloc. Windows and WASI need an allocator.

1 Like