authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-12-23 22:40:17-08:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-12-23 22:40:17-08:00
log2708a3c1ac9f63cce10b70c780dd7b1530d9c26b
treedbbb985cfebfe8379850c0fa4495aaf739de97ca
parentc9a609a61a0ebf195780dfdd84bb8ccead67f61f

fix the guess number game example


1 files changed, 13 insertions(+), 8 deletions(-)

  • foldertest
test/standalone/simple/guess_number/main.zig+13-8
......@@ -14,7 +14,10 @@ pub fn main() !void {
1414
1515 var stdout_writer = std.Io.File.stdout().writerStreaming(io, &.{});
1616 const out = &stdout_writer.interface;
17 const stdin: std.Io.File = .stdin();
17
18 var line_buffer: [20]u8 = undefined;
19 var stdin_reader: std.Io.File.Reader = .init(.stdin(), io, &line_buffer);
20 const in = &stdin_reader.interface;
1821
1922 try out.writeAll("Welcome to the Guess Number Game in Zig.\n");
2023
......@@ -22,13 +25,15 @@ pub fn main() !void {
2225
2326 while (true) {
2427 try out.writeAll("\nGuess a number between 1 and 100: ");
25 var line_buf: [20]u8 = undefined;
26 const amt = try stdin.read(&line_buf);
27 if (amt == line_buf.len) {
28 try out.writeAll("Input too long.\n");
29 continue;
30 }
31 const line = std.mem.trimEnd(u8, line_buf[0..amt], "\r\n");
28 const untrimmed_line = in.takeSentinel('\n') catch |err| switch (err) {
29 error.StreamTooLong => {
30 try out.writeAll("Line too long.\n");
31 _ = try in.discardDelimiterInclusive('\n');
32 continue;
33 },
34 else => |e| return e,
35 };
36 const line = std.mem.trimEnd(u8, untrimmed_line, "\r\n");
3237
3338 const guess = std.fmt.parseUnsigned(u8, line, 10) catch {
3439 try out.writeAll("Invalid number.\n");