2

Possible Duplicate:
std::string formatting like sprintf

Can I use the c++ iostream classes with a format string like printf?

Basically, I want to be able to do something like :-

snprintf (inchars, len, "%4f %6.2f %3d \n", float1, float2, int1);

easily using stringstreams. Is there an easy way to do this?

1
  • 1
    standard C++ formats are much more verbose, sadly. You're going to want a library. Commented Sep 25, 2012 at 18:35

3 Answers 3

5

Yes, there's the Boost Format Library (which is stringstreams internally).

Example:

#include <boost/format.hpp>
#include <iostream>

int main() {
  std::cout << boost::format("%s %s!\n") % "Hello" % "World";
  return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Wow, what a terrible syntax...
this looks like it will work... although i'll hold out for a while hoping for a better solution with a cleaner syntax.
You get used to it ... However, there are rare cases where you can get trouble with operator precedence because of this approach.
The use of % was probably inspired by python
2

You can write a wrapper function that returns something that you can deliver into an ostringstream.

This function combines some of the solutions presented in the link moooeeeep pointed out in comments:

std::string string_format(const char *fmt, ...) {
    std::vector<char> str(100);
    va_list ap;
    while (1) {
        va_start(ap, fmt);
        int n = vsnprintf(&str[0], str.size(), fmt, ap);
        va_end(ap);
        if (n > -1 && n < str.size()) {
            str.resize(n);
            return &str[0];
        }
        str.resize(str.size() * 2);
    }
}

3 Comments

nice. Here's a link to play around: ideone.com/23xIY
I just discovered a downside of this: when you pass in a format string that doesn't match the arguments supplied, you get rather unspecific errors, ranging from printed garbage to segmentation faults. boost::format provides a helpful error message instead. See this: ideone.com/63BK1
@moooeeeep: GCC provides an extension attribute that would warn about mismatched parameters to printf arguments (__attribute__((format(...)))).
0

This kind of formatting takes quite a bit more effort using standard C++ streams. In particular, you have to use stream manipulators which can specify the number of digits to show after the decimal place.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.