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?

Community
  • 1
  • 1
owagh
  • 3,428
  • 2
  • 31
  • 53

3 Answers3

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;
}
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
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);
    }
}
Community
  • 1
  • 1
jxh
  • 69,070
  • 8
  • 110
  • 193
  • 1
    nice. Here's a link to play around: http://ideone.com/23xIY – moooeeeep Sep 25 '12 at 19:28
  • 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: http://ideone.com/63BK1 – moooeeeep Oct 01 '12 at 11:05
  • @moooeeeep: GCC provides an extension attribute that would warn about mismatched parameters to printf arguments (`__attribute__((format(...)))`). – jxh Oct 01 '12 at 15:21
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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268