我希望找到一种快速整洁的方式以漂亮的表格格式打印,使单元格正确对齐。
C++中是否有一种方便的方法可以创建特定长度的子字符串字符串,类似于Python format的功能?
"{:10}".format("some_string")
我希望找到一种快速整洁的方式以漂亮的表格格式打印,使单元格正确对齐。
C++中是否有一种方便的方法可以创建特定长度的子字符串字符串,类似于Python format的功能?
"{:10}".format("some_string")
std::format
}},它将Python样式的格式应用到C++中:auto s = std::format("{:10}", "some_string");
在它广泛可用之前,您可以使用开源的{fmt}格式化库,std::format
基于此。
声明: 我是 {fmt} 和 C++20 std::format
的作者。
试一下这个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");
std::ostringstream stream;
stream << "substring";
std::string new_string = stream.str();
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
}
用作
char buf[100];
char str[] = "Hello";
format_string(str, buf, sizeof(buf));
printf(buf);
如果您无法像上面提到的那样使用 fmt,则最好的方法是使用一个格式化的包装类。以下是我曾经做过的:
#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;
}
然后您可以将其用作std::cout << table_entry("some_string", 10)
。 您可以根据需要调整table_entry
。 如果您没有类模板参数推断,可以实现make_table_entry
函数进行模板类型推断。
format_guard
是必需的,因为std::ostream
上的某些格式选项是粘性的。