C ++ string formatting like Python "{}". Format
Try this https://github.com/fmtlib/fmt
fmt::printf("Hello, %s!", "world"); // uses printf format string syntax
std::string s = fmt::format("{0}{1}{0}", "abra", "cad");
source to share
If you cannot use fmt as mentioned above, the best way would be to use a wrapper class for formatting. Here's what I did once:
#include <iomanip>
#include <iostream>
class format_guard {
std::ostream& _os;
std::ios::fmtflags _f;
public:
format_guard(std::ostream& os = std::cout) : _os(os), _f(os.flags()) {}
~format_guard() { _os.flags(_f); }
};
template <typename T>
struct table_entry {
const T& entry;
int width;
table_entry(const T& entry_, int width_)
: entry(entry_), width(static_cast<int>(width_)) {}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const table_entry<T>& e) {
format_guard fg(os);
return os << std::setw(e.width) << std::right << e.entry;
}
And then you will use it like std::cout << table_entry("some_string", 10)
. You can adapt table_entry
to your needs. If you don't have an inference of the class template argument, you can implement a function make_table_entry
to inference the template type.
This parameter is format_guard
required because some of the formatting options in std::ostream
are sticky.
source to share
you can quickly write a simple function to return a fixed length string.
We consider that the str string is null terminated, buf is already defined before the function call.
void format_string(char * str, char * buf, int size)
{
for (int i=0; i<size; i++)
buf[i] = ' '; // initialize the string with spaces
int x = 0;
while (str[x])
{
if (x >= size) break;
buf[x] = str[x]; // fill up the string
}
buf[size-1] = 0; // termination char
}
Used like
char buf[100];
char str[] = "Hello";
format_string(str, buf, sizeof(buf));
printf(buf);
source to share