Newbie here,
I’m facing an issue with the below code and I’m not sure is it a bug in the language or am I missing something.
const std = @import("std");
pub fn main() !void {
var counter: u8 = 0;
while (counter < 2) : (counter += 1) {
try println(intToStr(counter));
}
}
fn println(str: []const u8) !void {
const stdout = std.io.getStdOut().writer();
// try std.fmt.format(stdout, "{any}\n", .{str});
// this is using format inside
try stdout.print("{u}\n", .{str});
}
/// Calculate the number of digits required for a given integer type
fn maxDigitsForType(comptime T: type) comptime_int {
return std.math.log10(std.math.maxInt(T)) + 1;
}
pub fn intToStr(n: usize) []const u8 {
var buffer: [maxDigitsForType(@TypeOf(n))]u8 = undefined;
// NOTE: If you want to make the buffer c-compatible you could use bufPrintZ instead
const result = std.fmt.bufPrintZ(buffer[0..], "{d}", .{n}) catch unreachable;
return @as([]const u8, result);
}
when I try to print using try stdout.print("{u}\n", .{str});
I get a very weird behaviour:
{ ý }
{ ý }
wassou@was-pc:~/Projects/zig/bb_testing$ ./main
{ þ }
{ þ }
wassou@was-pc:~/Projects/zig/bb_testing$ ./main
{ ÿ }
{ ÿ }
everytime I execute I get different output.
but when I use std.fmt.format directly:
fn println(str: []const u8) !void {
const stdout = std.io.getStdOut().writer();
try std.fmt.format(stdout, "{u}\n", .{str});
// this is using format inside
// try stdout.print("{u}\n", .{str});
}
I get the expected output:
{ 0 }
{ 1 }
wassou@was-pc:~/Projects/zig/bb_testing$ ./main
{ 0 }
{ 1 }