| ... | ... | @@ -14,7 +14,10 @@ pub fn main() !void { |
| 14 | 14 | |
| 15 | 15 | var stdout_writer = std.Io.File.stdout().writerStreaming(io, &.{}); |
| 16 | 16 | 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; |
| 18 | 21 | |
| 19 | 22 | try out.writeAll("Welcome to the Guess Number Game in Zig.\n"); |
| 20 | 23 | |
| ... | ... | @@ -22,13 +25,15 @@ pub fn main() !void { |
| 22 | 25 | |
| 23 | 26 | while (true) { |
| 24 | 27 | 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"); |
| 32 | 37 | |
| 33 | 38 | const guess = std.fmt.parseUnsigned(u8, line, 10) catch { |
| 34 | 39 | try out.writeAll("Invalid number.\n"); |