简体   繁体   English

使用 {fmt} 引用字符串

[英]Quote a string using {fmt}

Is there any way to print a string as quoted using {fmt} ?有什么方法可以打印使用{fmt}引用的字符串?

Here is an example code showing what I want to achieve:这是一个示例代码,显示了我想要实现的目标:

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

I want the code to print Hello "Terens"!我希望代码打印Hello "Terens"! instead of just Hello Terens!而不仅仅是Hello Terens! . .

EDIT: I want to use the API for printing different data not known beforehand (I am writing this for a library, so I specifically want a quoted output when the data is a std::string or std::string_view .编辑:我想使用 API 打印事先未知的不同数据(我正在为一个库编写这个,所以当数据是std::stringstd::string_view

You can either wrap "{}" in quotes in the format string or use std::quoted .您可以在格式字符串中将 "{}" 用引号括起来,也可以使用std::quoted For example ( https://godbolt.org/z/f6TTb5 ):例如( https://godbolt.org/z/f6TTb5 ):

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

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

Output: Output:

Hello "Terens"!

I want to use the API for printing different data not known beforehand (I am writing this for a library, so I specifically want a quoted output when the data is a std::string or std::string_view.我想使用 API 打印事先未知的不同数据(我正在为一个库编写这个,所以当数据是 std::string 或 std::string_view 时,我特别想要一个引用的 output。

The following code:以下代码:

#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

It should be enough to get you started.这应该足以让你开始。

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

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