#Pls help

1 messages · Page 1 of 1 (latest)

ionic oyster
#

Code:

const std = @import("std");

pub fn main() !void {
    var input: [128]u8 = undefined;
    const stdin = std.io.getStdIn().reader();
    const stdout = std.io.getStdOut().writer();

    _ = stdin.readUntilDelimiter(&input, '\n') catch |err| {
        if (err == error.StreamTooLong) {
            try stdout.print("Input is too long!\n", .{});
            return;
        } else {
            return err;
        }
    };

    _ = try stdout.print("User entered: {s}\n", .{input});

    const input_slice = input[0..input.len];

    if (std.mem.eql(u8, input_slice, "a")) {
        _ = try stdout.print("Awesome", .{});
    } else if (std.mem.eql(u8, input_slice, "b")) {
        _ = try stdout.print("Best", .{});
    } else if (std.mem.eql(u8, input_slice, "c")) {
        _ = try stdout.print("Cool", .{});
    } else {
        _ = try stdout.print("Bad input value", .{});
    }
}

Output:

a
User entered: a
������������������������������������������������������������������������������������������������������������������������������
Bad input value⏎      

Expected Output:

a
User entered: a
Awesome
glacial marsh
#

Because you shouldn't be ignoring the return value of functions. You're printing the entire array when all the values haven't been written to. readUntilDelimiter returns the slice of input