1

I'm trying to figure out how to use a runtime-defined list in a C++ sprintf call on a run-defined string. The string will already have the tokens in there, I just need to somehow make the call for it to match as many args as it can in the string. Basically to compile the 4 calls below into a single call that would work for all of them, something along the lines of sprintf (buffer, "This is my string with args %i", myvec).

std::vector<int> myvec = {0, 1, 2, 3, 4};

char buffer [500];

sprintf (buffer, "This is my string with args %i", myvec[0], myvec[1], myvec[2], myvec[3], myvec[4]);

sprintf (buffer, "This is my string with args %i %i", myvec[0], myvec[1], myvec[2], myvec[3], myvec[4]);

sprintf (buffer, "This is my string with args %i %i %i", myvec[0], myvec[1], myvec[2], myvec[3], myvec[4]);

sprintf (buffer, "This is my string with args %i %i %i %i", myvec[0], myvec[1], myvec[2], myvec[3], myvec[4]); 

I've spoken to my colleagues and they don't think anything like that exists, so I thought I'd put it out there. Any ideas?

walshy002000
  • 99
  • 1
  • 10
  • I guess I don't quite follow. How would the function know how many arguments there were? Do you mean perhaps `sprintf(buffer, "This is my string with args %i", myvec, 4);` or something like that? – David Schwartz Apr 23 '12 at 01:52
  • You might want to look into string streams at some point - `sprintf` is one of those legacy-C things left in the C++ language but it's not type-extensible. Then you could create your own wrapper around vector and just do: `ss << myvecwrappervar;`. There are far too many C coders masquerading as C++ ones :-) – paxdiablo Apr 23 '12 at 02:13

2 Answers2

1

At least if I understand what you're trying to accomplish, I'd start with something like this:

std::ostringstream stream("This is my string with args ");

std::copy(myvec.begin(), myvec.end(), std::ostream_iterator<int>(stream, " "));

// stream.str() now contains the string.

As written, this will append an extra space to the end of the result string. If you want to avoid that, you can use the infix_ostream_iterator I posted in a previous answer in place of the ostream_iterator this uses.

Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

You could do it yourself. Make a function that takes a vector and returns the proper string. I don't have time to test it, but:

string vecToString (const vector<int> &v)
{
    string ret = "This is my string with args ";

    for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
    {
        istringstream ss;
        ss << *it;
        ret += ss.str() + (it != v.end() ? " " : "");
    }

    return ret;
}
chris
  • 60,560
  • 13
  • 143
  • 205