I have a const std::vector<char>
- not null-terminated. I want to print it using the fmt library, without making a copy of the vector.
I would have hoped that specifying the precision would suffice, but the fmt documentation says that :
Note that a C string must be null-terminated even if precision is specified.
Well, mine isn't. Must I make a copy and pad it with \0
, or is there something else I can do?
CodePudding user response:
If you could upgrade to C 17, then you could use a strig view argument instead of pointer to char:
const std::vector<char> v;
std::string_view sv(v.data(), v.size());
fmt::format("{}", sv);
CodePudding user response:
fmt accepts two kinds of "strings":
- C-style - just a pointer, must be null-terminated.
std::string
-like - data length.
Since C 17, C officially has the reference-type, std::string
-like string view class, which could refer to your vector-of-chars. (without copying anything) - and fmt
can print these. Problem is, you may not be in C 17. But fmt
itself also has to face this problem internally, so it's actually got you covered:
const std::vector<char> v;
fmt::internal::std_string_view sv(v.data(), v.size());
auto str = fmt::format("{}", sv);
Thanks @eerorika for making me thing of string views.