0

I'm trying to create a simple template engine, an engine that takes a pattern and some variable and produces a string output. This is the idea:

const char * pattern = ReadPattern(); // pattern is like "%s in %s ft"
vector<const char *> variable = ReadVariable(); // variable is like "6", "5".

How can I call printf function with them? Ideally I can do printf(pattern, variable[0], variable[1]); But because both pattern and variable are not known until runtime, I don't even know the number of variable. To my understanding, constructing a va_list programmingly is a not portable.

Please help, Thank you!

glglgl
  • 89,107
  • 13
  • 149
  • 217
yufanyufan
  • 171
  • 1
  • 7
  • http://stackoverflow.com/questions/988290/populating-a-va-list – ctn Jun 12 '13 at 22:34
  • But the best answer to "populating-a-va-list" is "This is a bad idea..." – yufanyufan Jun 12 '13 at 22:37
  • Generating patterns in runtime for printf() is most likely a VERY bad idea. That usually leads to security issues. See https://en.wikipedia.org/wiki/Uncontrolled_format_string – kpaleniu Jun 12 '13 at 22:55

1 Answers1

1

If you have an upper bound on the number of vector elements, it is relatively straight forward. Suppose the upper bound is 3:

int printf_vector(const char *p, vector<const char *> v) {
    switch (v.size()) {
    case 0: return printf(p);
    case 1: return printf(p, v[0]);
    case 2: return printf(p, v[0], v[1]);
    case 3: return printf(p, v[0], v[1], v[2]);
    default: break;
    }
    return -E2BIG;
}

If you have no upper bound, then this is a bad idea.

Community
  • 1
  • 1
jxh
  • 69,070
  • 8
  • 110
  • 193
  • 1
    In theory, you could look at the assembly output for the code, and figure out how to write an inline assembly loop to push the vector elements on to the stack and call `printf`. – jxh Jun 12 '13 at 23:00