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 and stdout. 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();
readUntilDelimiteris storing it’s data in the buffer, which is why you see it printed out before the garbage characters in your initial example. It’s returning a slice pointing to that data with a length.
I do not know what’s causing the second issue as I cannot reproduce it. I’m using 0.14.0-dev.364+8ab70f80c, so I suppose your version could have a bug. I would update to the latest master version and retry it.
EDIT: Strange. Now it seems to be working. Might’ve just been a weird one-off glitch.
EDIT 2: Nevermind, it’s still happening. I’ll open up a new thread for this.
Using zig version 0.17.0 reading from stdin and writing to stdout is something different because of buffering. In new zig versions your code is out of date and it will not compile. Here is the new starting code.
(If you don’t need buffering than you can use an empty buffer .{})
pub fn main(init: std.process.Init) !void {
var stdin_buffer: [1024]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(init.io, &stdin_buffer);
const stdin = &stdin_reader.interface;
var stdout_buffer: [1024]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &stdout_buffer);
const stdout = &stdout_writer.interface;
try stdout.print("Give me an input: ", .{}); try stdout.flush();
const line = try stdin.takeDelimiterExclusive('\n');
// print to the screen what was in the buffer before the program terminates
defer stdout.flush() catch {};
try stdout.print("Hello user.\n", .{});
}