-1

I need to format string at runtime in C or C++ (but not with boost like this example).
For example: at runtime I am getting as input string like this "hello world %d %u %s" and array with values. I have to print the formatted string.

I am looking for solution at c, c++ or std::function.
Does anyone have an idea for me?
Thanks in advance

EDIT: array with values means an array of char that stores the values byte by byte. in the above example the four first bytes will be an the first argument %d, the next four bytes will be the value of %u and so on.

Community
  • 1
  • 1
RRR
  • 3,937
  • 13
  • 51
  • 75
  • Maybe you need something like [this](http://ideone.com/CwDEUU)? Or I misinterpret your question? – Ivaylo Strandjev Mar 31 '14 at 10:22
  • "array with values"? show code example. – Karoly Horvath Mar 31 '14 at 10:26
  • C and C++ are two distinct languages. Use ONE of them. std::function... what do you mean by that? – thecoshman Mar 31 '14 at 11:00
  • It's pretty complicated to implement your own printf. For example are you supporting `%-3.6s` and `%04llu` ? If instead you are only supporting a set number of tokens such as `%d` etc. then just parse your string for these things and act on them when you find them. – M.M Apr 06 '14 at 11:21

2 Answers2

1

In C, that's not directly possible, unless your "array of values" is a va_list value in which case you just need to call vsnprintf().

The problem otherwise is that there is no typical way in C to represent "an array of values" of different (native) types.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

If you will know the set of values early on, but need to save them in a container until the format string to use is known, then you could convert them to strings before storing them in a vector<string>, then do the substitution using a simple find-next-%s / replace-with-next-vector-element loop.

If for some reason you want/need to keep the value's as a array of values with seemingly distinct types, and defer converting them to strings until later, then you must implement some manner of discriminated-union or polymorphic variant class, e.g.:

 struct Value
 {
     virtual ~Value() { }
     virtual std::string to_string() const = 0;
 };

 struct Int
 {
     Int(int x) : x_(x) { }
     std::string to_string() const override { return std::to_string(x); }
     int x_;
 };

 struct String
 {
     String(const std::string& x) : x_(x) { }
     std::string to_string() const override { return x_; }
     std::string x_;
 };

 std::vector<Value*> values;

You can then iterate over values calling to_string() to get text to substitute into your format string.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252