【问题标题】:Quote a string using {fmt}使用 {fmt} 引用字符串
【发布时间】:2021-06-07 10:42:39
【问题描述】:

有没有办法打印使用{fmt} 引用的字符串?

这是一个示例代码,显示了我想要实现的目标:

fmt::print("Hello {}!", "Terens");

我希望代码打印Hello "Terens"! 而不仅仅是Hello Terens!

编辑:我想使用 API 来打印事先未知的不同数据(我正在为一个库编写这个,所以当数据是 std::stringstd::string_view 时,我特别想要一个带引号的输出。

【问题讨论】:

  • "Hello \"{}\"!"R"(Hello "{}"!)"?
  • 我想将它用于不同的类型,但如果它是一个字符串,我想用引号将输出括起来。
  • 您可以将 "Terens" 更改为 "\"Terens\"" - 以及您希望在引号中输出的任何其他字符串
  • @ericpat 我不希望人们自己引用他们的字符串????。我想我会在格式字符串上使用is_string trait 和三元组。
  • Quote 方法在这里 create 新字符串(及其开销:-/),返回 QuoteWrapper<T> 将允许您的类型具有自定义点(实际上是您不能(即使可能也不应该)为外部类型添加(外部)自定义,至少应该是你的)。

标签: c++ fmt


【解决方案1】:

您可以在格式字符串中将“{}”括在引号中,也可以使用std::quoted。例如(https://godbolt.org/z/f6TTb5):

#include <fmt/ostream.h>
#include <iomanip>

int main(){
  fmt::print("Hello {}!", std::quoted("Terens"));
}

输出:

Hello "Terens"!

【讨论】:

  • 我完全忘记了std::quoted。看起来非常适合这种情况,谢谢!
【解决方案2】:

我想使用 API 来打印事先未知的不同数据(我正在为一个库编写这个,所以当数据是 std::string 或 std::string_view 时,我特别想要一个带引号的输出。

以下代码:

#include <fmt/core.h>

template<typename T>
const T& myprint_get(const T& t) {
    return t;
}
std::string myprint_get(const std::string& t) {
    return "\"" + t + "\"";
}

template<typename ...T>
void myprint(const char *fmt, T... t) {
    fmt::print(fmt, myprint_get(t)...);
}

int main() {
    myprint("{} {}", std::string("string"), 5);
}

outputs:

"string" 5

应该足以让您入门。

【讨论】:

  • 优秀的解决方案。我想我会使用fmt::format 而不是"\"" + str "\"",因为我希望它也可以与std::string_view 一起使用。
  • fmt::format 只是后缀/前缀",只是"\"" + std::string(str) + "\"" 复制字符串是浪费cpu。
猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多