简体   繁体   English

如何使用 fmt 打印字符向量?

[英]How do I print a vector of chars using fmt?

I have a const std::vector<char> - not null-terminated.我有一个const std::vector<char> -不是以空值结尾的。 I want to print it using the fmt library, without making a copy of the vector.我想使用 fmt 库打印它,而不复制矢量。

I would have hoped that specifying the precision would suffice, but the fmt documentation says that :我希望指定精度就足够了,但是 fmt 文档说:

Note that a C string must be null-terminated even if precision is specified.请注意,即使指定了精度,C 字符串也必须以空值结尾。

Well, mine isn't.嗯,我的不是。 Must I make a copy and pad it with \0 , or is there something else I can do?我必须制作一个副本并用\0填充它,还是我能做些什么?

If you could upgrade to C++17, then you could use a strig view argument instead of pointer to char:如果您可以升级到 C++17,那么您可以使用字符串视图参数而不是指向 char 的指针:

const std::vector<char> v;
std::string_view sv(v.data(), v.size());
fmt::format("{}", sv);

What about using fmt::join ?使用fmt::join怎么样?

Returns a view that formats range with elements separated by sep.返回一个视图,该视图使用以 sep 分隔的元素格式化范围。

[Demo] [演示]

#include <fmt/ranges.h>
#include <vector>

int main() {
    std::vector<char> v{'a', 'b', 'c'};
    fmt::print("{}", fmt::join(v, ""));
}

// Outputs:
//
//   abc

fmt accepts two kinds of "strings": fmt 接受两种“字符串”:

  • C-style - just a pointer, must be null-terminated. C 风格- 只是一个指针,必须以空值结尾。
  • std::string -like - data + length. std::string类似- 数据 + 长度。

Since C++17, C++ officially has the reference-type, std::string -like string view class, which could refer to your vector-of-chars.从 C++17 开始,C++ 正式具有引用类型std::string类似的字符串视图类,它可以引用您的字符向量。 (without copying anything) - and fmt can print these. (不复制任何东西)- fmt可以打印这些。 Problem is, you may not be in C++17.问题是,您可能不在 C++17 中。 But fmt itself also has to face this problem internally, so it's actually got you covered - in whatever version of the standard you can get fmt itself to compile, in particular C++14:但是fmt本身也必须在内部面对这个问题,所以它实际上已经涵盖了你- 在任何版本的标准中你都可以让 fmt 本身编译,特别是 C++14:

const std::vector<char> v;
fmt::string_view sv(v.data(), v.size());
auto str = fmt::format("{}", sv);

Thanks @eerorika for making me think of string views.感谢@eerorika 让我想到了字符串视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM