| ... | @@ -14,7 +14,10 @@ pub fn main() !void { | ... | @@ -14,7 +14,10 @@ pub fn main() !void { |
| 14 | | 14 | |
| 15 | var stdout_writer = std.Io.File.stdout().writerStreaming(io, &.{}); | 15 | var stdout_writer = std.Io.File.stdout().writerStreaming(io, &.{}); |
| 16 | const out = &stdout_writer.interface; | 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 | try out.writeAll("Welcome to the Guess Number Game in Zig.\n"); | 22 | try out.writeAll("Welcome to the Guess Number Game in Zig.\n"); |
| 20 | | 23 | |
| ... | @@ -22,13 +25,15 @@ pub fn main() !void { | ... | @@ -22,13 +25,15 @@ pub fn main() !void { |
| 22 | | 25 | |
| 23 | while (true) { | 26 | while (true) { |
| 24 | try out.writeAll("\nGuess a number between 1 and 100: "); | 27 | try out.writeAll("\nGuess a number between 1 and 100: "); |
| 25 | var line_buf: [20]u8 = undefined; | 28 | const untrimmed_line = in.takeSentinel('\n') catch |err| switch (err) { |
| 26 | const amt = try stdin.read(&line_buf); | 29 | error.StreamTooLong => { |
| 27 | if (amt == line_buf.len) { | 30 | try out.writeAll("Line too long.\n"); |
| 28 | try out.writeAll("Input too long.\n"); | 31 | _ = try in.discardDelimiterInclusive('\n'); |
| 29 | continue; | 32 | continue; |
| 30 | } | 33 | }, |
| 31 | const line = std.mem.trimEnd(u8, line_buf[0..amt], "\r\n"); | 34 | else => |e| return e, |
| | 35 | }; |
| | 36 | const line = std.mem.trimEnd(u8, untrimmed_line, "\r\n"); |
| 32 | | 37 | |
| 33 | const guess = std.fmt.parseUnsigned(u8, line, 10) catch { | 38 | const guess = std.fmt.parseUnsigned(u8, line, 10) catch { |
| 34 | try out.writeAll("Invalid number.\n"); | 39 | try out.writeAll("Invalid number.\n"); |