Skip to content

Commit 16f33c6

Browse files
committed
fix read-line test / closes #314
1 parent 1b8aa0a commit 16f33c6

File tree

1 file changed

+14
-25
lines changed

1 file changed

+14
-25
lines changed

website/versioned_docs/version-0.15.x/02-standard-library/04-readers-and-writers.mdx

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ will return `error.StreamTooLong`.
2323

2424
A common usecase for readers is to read until the next line (e.g. for user
2525
input). 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)
2727
file.
2828

2929
{/* Code snippet not tested as it uses stdin/stdout */}
@@ -34,33 +34,22 @@ const std = @import("std");
3434
const expect = std.testing.expect;
3535
const 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

Comments
 (0)