What is Zig analog for C sprintf()?

Hi.

I want to form a string in memory, as in C:

char buf[32];
int k = 7;
sprintf(buf, "item-%d", k);

But I do not understand what tools from stdlib should be used for that :frowning:
Will be glad to see some advice.

std.fmt.bufPrint is what you want:

const std = @import("std");

pub fn main() !void {
   var buf: [32]u8 = undefined;
   const slice = try std.fmt.bufPrint(&buf, "Hello {s}", .{"World!"});
   std.log.info("{s}", .{slice});
}

Note that bufPrint returns a slice to the bytes written into buf, so it’s linked to buf and if buf changes or is freed, slice will reflect those changes or will be invalid.

5 Likes

std.fmt.allocPrint should also be mentioned. Which to use depends on the desired behavior.

  • std.fmt.bufPrint prints to a pre-allocated buffer, saving a runtime allocation
  • std.fmt.allocPrint requires a runtime allocation, but might be more appropriate if the length required cannot be reliably guessed at compile time.
4 Likes

Thanks @jeang3nie for your note. However, bufPrint was more suitable for my case.

2 Likes