So as a simple exercise to familiarize myself with Zig, I have decided to write a simple game ov hangman.
The first thing I want to do, before anything, is make sure I have a well-functioning user-input system; however, for some reason, my code takes input once and gets stuck printing that, when it is actually supposed to be taking input every loop iteration.
This is my program so far:
const GPAllocConfig = std.heap.GeneralPurposeAllocatorConfig;
const GPAllocator = std.heap.GeneralPurposeAllocator;
const HangmanGame = @import("hangman.zig").HangmanGame;
const Reader = std.fs.File.Reader;
const Writer = std.fs.File.Writer;
const std = @import("std");
pub fn main() !void {
var allocator = GPAllocator(.{}).init;
defer _ = allocator.deinit();
var stdout_buf:[256]u8 = undefined;
var stdin_buf:[256]u8 = [_]u8 {0} ** 256;
var stdout:Writer = std.fs.File.stdout().writer(&stdout_buf);
var stdin:Reader = std.fs.File.stdin().reader(&stdin_buf);
try stdout.interface.writeAll("Welcome to hangman- in Zig!\n");
try stdout.interface.flush();
var allocating_writer = std.Io.Writer.Allocating.init(allocator.allocator());
defer allocating_writer.deinit();
while (true) {
_ = stdin.interface.streamDelimiter(&allocating_writer.writer, '\n') catch { continue; };
try allocating_writer.writer.flush();
try stdout.interface.writeAll(allocating_writer.written());
try stdout.interface.writeByte('\n');
try stdout.interface.flush();
}
}
If I write "test", it just spams "test" (with a newline).
If I add defer allocating_writer.writer.end = 0 to the loop and write "test", a bunch ov blank lines are printed instead ov what is inputted.
My hypothesis is that the error is related to the buffer contained by allocating_writer.writer, and I am guessing the solution is to clear the buffer, but I am not quite sure what the best way to do that – with respect to the other facets ov the API – is.