22

我正在寻找一种快速而简洁的方法来打印一个漂亮的表格格式,并且单元格被正确对齐。

c++ 中是否有一种方便的方法来创建具有一定长度的子字符串,如 python 格式

"{:10}".format("some_string")
4

6 回答 6

38

在 C++20 中,您将能够使用std::format它为 C++ 带来类似 Python 的格式:

auto s = std::format("{:10}", "some_string");

在此之前,您可以使用基于的开源{fmt} 格式化库std::format

免责声明:我是 {fmt} 和 C++20 的作者std::format

于 2020-01-26T02:40:04.393 回答
28

试试这个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");
于 2017-06-30T05:01:30.007 回答
6

你在这里有很多选择。例如使用流。

源码.cpp

  std::ostringstream stream;
  stream << "substring";
  std::string new_string = stream.str();
于 2017-06-30T04:59:49.070 回答
3

@mattn 是正确的, https: //github.com/fmtlib/fmt 上的 fmt 库正好提供了这个功能。

令人兴奋的消息是这已被 C++20 标准所接受。

您可以使用 fmt 库,知道它将是 C++20 中的 std::fmt

https://www.zverovich.net/2019/07/23/std-format-cpp20.html https://en.cppreference.com/w/cpp/utility/format/format

于 2019-12-18T23:52:45.813 回答
0

您可以快速编写一个简单的函数来返回一个固定长度的字符串。

我们认为str字符串以 null 结尾,在调用函数之前已经定义了 buf。

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);
于 2017-06-30T06:55:22.733 回答
-1

如果您不能如上所述使用 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是粘性的。

于 2018-12-17T19:33:52.197 回答