Force UTF-8 handling for std::string in fmt

Viewed 618

In my C++17 project, I have a std::string which is known to contain UTF-8 encoded data. Is there any way to force fmt to treat its data as UTF-8 such that this works as expected?

fmt::print("{:-^11}", "あいう");
// should print "----あいう----", currently prints "-あいう-"
2 Answers

UTF-8 handling in {fmt} was recently improved and your example now works with the master branch:

#include <fmt/core.h>

int main() {
  fmt::print("{:-^11}", "あいう");
}

prints

----あいう----

Pass field width as the next argument and calculate it yourself:

#include <fmt/format.h>
#include <cstring>
int main() {
    fmt::print("{:-^{}}", "あいう", 8 + std::strlen("あいう"));
}
Related