Closed
Description
With fmt-4.x, I often append multiple formatted stuffs to a fixed buffer in a quite neat way like this:
char buff[1024];
// I know declare like buff[1024]{} or something like that can eliminate appending zero to the end.
fmt::ArrayWriter fmter(buff);
fmter.Write("{}, ", 42);
if (condition1) {
fmter.Write("{}, ", .42);
}
if (condition2) {
fmter.Write("{}, ", "string-blah");
}
// this is convenient function to append zero to the end
fmter.c_str();
// buff contains: "42, .42, string-blah, ";
With fmt-5.0, ArrayWriter and MemoryWriter are somehow replaced by format_to_n().
Though with a single format, the new version looks better then previous one,
it is quite clumsy compare to the previous version in case someone needs to format multiple times with different things.
This is what I have tried to do the same with the new version:
char buff[1024];
size_t fmtsize = 0;
auto result = fmt::format_to_n(buff, std::size(buff) - 1 - fmtsize, "{}, ", 42);
fmtsize += result.size;
if (condition1) {
result = fmt::format_to_n(result.out, std::size(buff) - 1 - fmtsize, "{}, ", .42);
fmtsize += result.size;
}
if (condition2) {
result = fmt::format_to_n(result.out, std::size(buff) - 1 - fmtsize, "{}, ", "string-blah");
fmtsize += result.size;
}
// truncates trash
buff[fmtsize] = 0;
// buff contains: "42, .42, string-blah, ";
I wonder if there is another better way to make it neater?.
Thanks.
Update:
To avoid opening a new issue, I would append more thing here.
I realize that the fmt::format_to_n() does not support wchar_t also.
MSVS 2017 15.7 cannot compile calls below:
wchar_t buff[32];
auto res1 = fmt::format_to_n(buff, std::size(buff) - 1, L"{}", L"Wchar");
// even this fail also
auto res2 = fmt::format_to_n(buff, std::size(buff) - 1, "{}", L"Wchar");
Metadata
Assignees
Labels
No labels
Activity