Quote a string using {fmt}

Viewed 692

Is there any way to print a string as quoted using {fmt}?

Here is an example code showing what I want to achieve:

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

I want the code to print Hello "Terens"! instead of just 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.

2 Answers

You can either wrap "{}" in quotes in the format string or use std::quoted. For example (https://godbolt.org/z/f6TTb5):

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

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

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.

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.

Related