#Print null terminated string in array properly

1 messages · Page 1 of 1 (latest)

hasty aspen
#

Hello there,

When I read some string to buffer like this:

const std = @import("std");

pub fn main() !void {
    var buff: [100]u8 = undefined;       
    const val = "Hello, world!";         
    std.mem.copyForwards(u8, &buff, val);
    std.debug.print("{s}\n", .{buff});   
}                                        

I get ugly output showed on screen. If I do the same in C I get normal output:

#include <stdio.h>
#include <memory.h>

int main() {
  char s[100];
  const char* s2 = "Hello, world!";

  memcpy(s, s2, 14);

  printf("%s\n", s);
  return 0;
}

How to make it print properly in zig, assuming that I don't know how much data was read into the buffer?

flint verge
#

std.debug.print("{s}\n", .{std.mem.sliceTo(&buff, 0)});

#

although you never put a zero in the buffer, so there's no way to know where the string ends