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?

2
  • 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? Commented Apr 23, 2012 at 1: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 :-) Commented Apr 23, 2012 at 2:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Definitely better than my solution :)
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.