C++字符串格式化,如Python“{}".format

oxiaedzo  于 2023-04-13  发布在  Python
关注(0)|答案(6)|浏览(159)

我正在寻找一个快速和整洁的方式打印在一个很好的表格格式与细胞被正确对齐。
在C++中是否有一种方便的方法来创建像Python格式那样具有一定长度的子字符串的字符串

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

ibps3vxo1#

在C20中,你可以使用std::format,它为C带来了类似Python的格式:

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

直到它被广泛使用,你可以使用开源的{fmt} formatting librarystd::format是基于。

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

3vpjnl9f

3vpjnl9f2#

试试这个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");
8i9zcol2

8i9zcol23#

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

source.cpp

std::ostringstream stream;
  stream << "substring";
  std::string new_string = stream.str();
u4vypkhs

u4vypkhs4#

@mattn是正确的,https://github.com/fmtlib/fmt上的fmt库正好提供了这个功能。
令人兴奋的消息是,这已经被接受到C20标准中。
在C
20中,您可以使用fmt库,因为它将是std::fmt
https://www.zverovich.net/2019/07/23/std-format-cpp20.htmlhttps://en.cppreference.com/w/cpp/utility/format/format

bn31dyow

bn31dyow5#

你可以快速编写一个简单的函数来返回一个固定长度的字符串。
我们考虑 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);
tjjdgumg

tjjdgumg6#

如果你不能像上面提到的那样使用fmt,最好的方法是使用一个 Package 器类来格式化。下面是我曾经做过的:

#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上的某些格式选项是粘性的。

相关问题