yufanyufan
yufanyufan

Reputation: 191

How to call printf with an array?

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!

Upvotes: 0

Views: 454

Answers (1)

jxh
jxh

Reputation: 70472

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.

Upvotes: 1

Related Questions