Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current Way to Get User Input in Zig

Tags:

zig

I'm following this blog post on 'comptime' in Zig.

The following line no longer compiles in Zig 0.6.0.

const user_input = try io.readLineSlice(buf[0..]);

Below is the full function:

fn ask_user() !i64 {
    var buf: [10]u8 = undefined;
    std.debug.warn("A number please: ");
    const user_input = try io.readLineSlice(buf[0..]);
    return fmt.parseInt(i64, user_input, 10);
}

What is the equivalent in the current version (of getting user input)?

like image 883
user3475861 Avatar asked Dec 23 '22 17:12

user3475861


1 Answers

You can use the method readUntilDelimiterOrEof of stdin instead:

const stdin = std.io.getStdIn().reader();
pub fn readUntilDelimiterOrEof(self: @TypeOf(stdin), buf: []u8, delimiter: u8) !?[]u8

So, the code can be:

fn ask_user() !i64 {
    const stdin = std.io.getStdIn().reader();
    const stdout = std.io.getStdOut().writer();

    var buf: [10]u8 = undefined;
    
    try stdout.print("A number please: ", .{});

    if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
        return std.fmt.parseInt(i64, user_input, 10);
    } else {
        return @as(i64, 0);
    }
}

See also: Zig 0.7.0 documentation.

like image 86
Cristobal Montecino Avatar answered Jan 18 '23 13:01

Cristobal Montecino