Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way of marrying sprintf and std::string in C++?

Very frequently in my C++ code I use the following type of helper function:

static inline std::string stringf(const char *fmt, ...)
{
    std::string ret;
    // Deal with varargs
    va_list args;
    va_start(args, fmt);
    // Resize our string based on the arguments
    ret.resize(vsnprintf(0, 0, fmt, args));
    // End the varargs and restart because vsnprintf mucked up our args
    va_end(args);
    va_start(args, fmt);
    // Fill the string
    if(!ret.empty())
    {
        vsnprintf(&ret.front(), ret.size() + 1, fmt, args);
    }
    // End of variadic section
    va_end(args);
    // Return the string
    return ret;
}

It has a few upsides:

  1. No arbitrary limits on string lengths
  2. The string is generated in-place and doesn't get copied around (if RVO works as it should)
  3. No surprises from the outside

Now, I have a few of problems with it:

  1. Kind of ugly with the rescanning of the varargs
  2. The fact that std::string is internally a contiguous string with space for a null terminator directly after it, does not seem to actually be explicitly stated in the spec. It's implied via the fact that ->c_str() has to be O(1) and return a null-terminated string, and I believe &(data()[0]) is supposed to equal &(*begin())
  3. vsnprintf() is called twice, potentially doing expensive throw-away work the first time

Does anybody know a better way?

like image 293
Yuriy Romanenko Avatar asked Jun 26 '15 02:06

Yuriy Romanenko


People also ask

What can I use instead of sprintf in C++?

This function is used to store something inside a string. The syntax is like the printf() function, the only difference is, we have to specify the string into it. In C++ also, we can do the same by using ostringstream.

Is Sprintf safe C?

Warning: The sprintf function can be dangerous because it can potentially output more characters than can fit in the allocation size of the string s . Remember that the field width given in a conversion specification is only a minimum value. To avoid this problem, you can use snprintf or asprintf , described below.

Is string the same as std :: string?

There is no functionality difference between string and std::string because they're the same type.


1 Answers

Are you married (pun intended) to std::sprintf()? If you are using C++ and the oh so modern std::string, why not take full advantage of new language features and use variadic templates to do a type safe sprintf that returns a std::string?

Check out this very nice looking implementation: https://github.com/c42f/tinyformat. I think this solves all your issues.

like image 56
Nir Friedman Avatar answered Oct 04 '22 01:10

Nir Friedman