So I have a couple issues:
const std = @import("std");
//const stdout = std.io.getStdOut().writer();
//const stdin = std.io.getStdIn().reader();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
//fn run_file(path: []const u8) !void {
//
//}
fn run_prompt() !void {
const stdout = std.io.getStdOut().writer();
const stdin = std.io.getStdIn().reader();
while (true) {
try stdout.print("> ", .{});
var buffer: [1024]u8 = undefined;
const result = try stdin.readUntilDelimiter(&buffer, '\n');
_ = result;
try stdout.print("{s}", .{buffer});
}
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const args = try std.process.argsAlloc(allocator);
if (args.len > 2) {
try stdout.print("Usage: {s} [path_to_script_file]", .{args[0]});
} else if (args.len == 2) {
//run_file(args[1]);
} else {
try run_prompt();
}
}
- The
buffer
array will successfully store input such as “test” but it will alsoa bunch of random characters.
The output is as such:
> test
test
¬¬¬¬¬¬¬¬¬¬¬¬¬...
As far as I understand, this is because unlike C/C++, strings in Zig are not null terminated. So it’s printing the entire array. What I’m wondering is if there’s a better way of getting input from a user.
- I am unable to have global objects
stdin
andstdout
. If I try to compile with these as global variables instead of variables scoped within a function, I get the following error:
└─ zig build-exe Zrox Debug native 1 errors
C:\zig-windows-x86_64-0.14.0-dev.186+8f20e81b8\lib\std\os\windows.zig:2107:28: error: unable to evaluate comptime expression
break :blk asm (
^~~
C:\zig-windows-x86_64-0.14.0-dev.186+8f20e81b8\lib\std\os\windows.zig:2122:15: note: called from here
return teb().ProcessEnvironmentBlock;
~~~^~
C:\zig-windows-x86_64-0.14.0-dev.186+8f20e81b8\lib\std\io.zig:23:27: note: called from here
return windows.peb().ProcessParameters.hStdOutput;
~~~~~~~~~~~^~
C:\zig-windows-x86_64-0.14.0-dev.186+8f20e81b8\lib\std\io.zig:34:40: note: called from here
return .{ .handle = getStdOutHandle() };
~~~~~~~~~~~~~~~^~
src\main.zig:2:32: note: called from here
const stdout = std.io.getStdOut().writer();
Why does this happen?