Skip to content
This repository has been archived by the owner on Aug 24, 2024. It is now read-only.

Commit

Permalink
Update sample code (#14)
Browse files Browse the repository at this point in the history
* Fix for windows

* Update 09-coding-in-zig.md
  • Loading branch information
cy-arctique authored Oct 16, 2023
1 parent 67cb037 commit f726cdc
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions 09-coding-in-zig.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ const User = struct {

```zig
const std = @import("std");
const builtin = @import("builtin");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
Expand All @@ -127,7 +128,14 @@ pub fn main() !void {
while (true) : (i += 1) {
var buf: [30]u8 = undefined;
try stdout.print("Please enter a name: ", .{});
if (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |name| {
if (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var name: []const u8 = line;
// Windows平台换行以`\r\n`结束
// 所以需要截取\r以获取控制台输入字符
if (builtin.os.tag == .windows) {
name = std.mem.trimRight(u8, line[0 .. line.len - 1], "\r");
}
if (name.len == 0) {
break;
}
Expand Down Expand Up @@ -216,6 +224,7 @@ defer {
```zig
const std = @import("std");
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
Expand All @@ -240,7 +249,12 @@ pub fn main() !void {
while (true) : (i += 1) {
var buf: [30]u8 = undefined;
try stdout.print("Please enter a name: ", .{});
if (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |name| {
if (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var name: []const u8 = line;
if (builtin.os.tag == .windows) {
name = std.mem.trimRight(u8, line[0 .. line.len - 1], "\r");
}
if (name.len == 0) {
break;
}
Expand Down

0 comments on commit f726cdc

Please sign in to comment.