I have a simple scene in C++ code.
I want to get a long string containing some repeated std::string_view; is there a way to achieve this without copying the string?
#include <cstdio>
#include <string_view>
struct Logger {
static inline constexpr std::string_view indent = " ";
static inline int level = 0;
Logger() {
level++;
}
// ...
void log(const std::string &msg) {
std::printf(/* repeat indent 'level' times */);
}
};
C-Style Solution
std::printfallows you to dynamically specify the field width. For example:This will output:
We can use this trick because indentation always consist of one character, so we don't really have to repeat a full
std::string_view. Obviously, this wouldn't work if you wanted indentation that is a mixture of multiple characters, but that would be highly unusual.Old-School C++ Solution
However, that is a very C-style solution, and you could just use a loop to avoid copying:
However, if the indent is not a mixture of different characters, we can do a similar trick using
std::coutas above to avoid this loop:If you absolutely insist on using
std::printf, we can still do:Your
indentstring can be printed exactly the same way.