Hey Everyone,
I am an “AI” Engineer (AI tooling). Most of my experience is in Python, and Typescript. Looking to escape web dev hell so I am learning zig! I have done all of this without AI pretty much which is a pretty big deal for me. I just started this project and learning zig yesterday so please bare with me!
Anyways, here’s my issue.
const std = @import("std");
const Io = std.Io;
const Gratitude = struct {
reason: []u8,
};
pub fn main(init: std.process.Init) !void {
var stdout_buffer: [1024]u8 = undefined;
var stdout_writer = Io.File.stdout().writer(init.io, &stdout_buffer);
const stdout: *std.Io.Writer = &stdout_writer.interface;
var stdin_buffer: [1024]u8 = undefined;
var stdin_reader = Io.File.stdin().reader(init.io, &stdin_buffer);
const stdin: *std.Io.Reader = &stdin_reader.interface;
try stdout.print("What are you grateful for?\n", .{});
try stdout.flush();
// 1, declare a 5 item array.
// 2, loop through said array until it has 5 items.
// 3, after user input, append the string to the array
// 4, once the length is 5, stop the loop.
//
var i: u8 = 1;
const allocator = std.heap.page_allocator;
var list_of_gratitudes: std.ArrayList([]const u8) = .empty;
defer list_of_gratitudes.deinit(allocator);
while (i <= 5) : (i += 1) {
try stdout.print("{d}: ", .{i});
try stdout.flush();
const raw_line = try stdin.takeDelimiter('\n') orelse unreachable;
const line = std.mem.trim(u8, raw_line, "\r");
try list_of_gratitudes.append(allocator, line);
}
for (list_of_gratitudes.items, 0..) |gratitude_string, index| {
try stdout.print("{d}: {s}\n", .{ index + 1, gratitude_string });
try stdout.flush();
}
try stdout.print("{s}\n", .{"Thank you, Have a nice day!"});
try stdout.flush();
}
When I enter 5 different strings:
What are you grateful for?
1: My keyboard
2: My daughter
3: My Wife
4: My Family
5: Zig
1: Zig
amily
r
2: Zig
amily
r
3: Zig
ami
4: Zig
amily
5: Zig
Thank you, Have a nice day!
As you can see the output is garbled. I have tried to use stdin.discardRemaining() and this leads to the loop not executing properly (it infinitely hangs). I have also tried using stdin.toss(1) (I don’t exactly understand what this does but anyways). I have a feeling that stdin is keeping old characters in it’s reader when I go to read the next user input which is what’s leading to this garbled output. Anyways, thank you all for your help and I hope this was enough context!
Will