C ++ string formatting like Python "{}". Format

I'm looking for a quick and neat way to print in a good table format with correctly aligned cells.

Is there a convenient way in C ++ to create substring strings with a specific length such as python format

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

      

+8


source to share


4 answers


You have many options here. For example using streams.

source.cpp



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

      

+3


source


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");

      

+10


source


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.

0


source


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);

      

-1


source







All Articles