Reputation: 99
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?
Upvotes: 1
Views: 524
Reputation: 490348
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.
Upvotes: 1
Reputation: 61970
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;
}
Upvotes: 0