@@ -23,7 +23,7 @@ will return `error.StreamTooLong`.
2323
2424A common usecase for readers is to read until the next line (e.g. for user
2525input). Here we will do this with the
26- [ ` std.io.getStdIn () ` ] ( https://ziglang.org/documentation/master /std/#std.io.getStdIn )
26+ [ ` std.fs.File.stdin () ` ] ( https://ziglang.org/documentation/0.15.2 /std/#std.fs.File.stdin )
2727file.
2828
2929{ /* Code snippet not tested as it uses stdin/stdout */ }
@@ -34,33 +34,22 @@ const std = @import("std");
3434const expect = std.testing.expect;
3535const eql = std.mem.eql;
3636// hide-end
37+ test "read until next line" {
38+ var stdout_buf: [1024]u8 = undefined;
39+ var stdout_writer = std.fs.File.stdout().writer(&stdout_buf);
40+ const stdout: *std.io.Writer = &stdout_writer.interface;
3741
38- fn nextLine(reader: anytype, buffer: []u8) !?[]const u8 {
39- var line = (try reader.readUntilDelimiterOrEof(
40- buffer,
41- '\n',
42- )) orelse return null;
43- // trim annoying windows-only carriage return character
44- if (@import("builtin").os.tag == .windows) {
45- return std.mem.trimRight(u8, line, "\r");
46- } else {
47- return line;
48- }
49- }
42+ var stdin_buf: [1024]u8 = undefined;
43+ var stdin_reader = std.fs.File.stdin().reader(&stdin_buf);
44+ const stdin: *std.io.Reader = &stdin_reader.interface;
5045
51- test "read until next line" {
52- const stdout = std.io.getStdOut();
53- const stdin = std.io.getStdIn();
46+ try stdout.writeAll("Enter your name\n");
47+ try stdout.flush();
5448
55- try stdout.writeAll(
56- \\ Enter your name:
57- );
49+ const bare_line = try stdin.takeDelimiter('\n') orelse unreachable;
50+ const line = std.mem.trim(u8, bare_line, "\r");
5851
59- var buffer: [100]u8 = undefined;
60- const input = (try nextLine(stdin.reader(), &buffer)).?;
61- try stdout.writer().print(
62- "Your name is: \"{s}\"\n",
63- .{input},
64- );
52+ try stdout.print("Your name is: \"{s}\"\n", .{line});
53+ try stdout.flush();
6554}
6655```
0 commit comments