4

Hey everyone! I'm trying to make a simple copy of sprintf that returns the formatted string, but I am coming into a small snag...

Apparently, using a variable-length argument list you cannot pass a std::string instance.

I already have the parser working properly with int, double, float, char, const char*, char*... I have yet to get strings to work. :\

In case you're wondering, this is the compile error I get: /root/learncpp/StringFormat/main.cpp:8: warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime

The main reason I'm doing this is so that I can have convenient formatting without having to rely on 3rd party libraries, yet still not have to append ".c_str()" to every string instance I use.

Help with this would be appreciated. Perhaps there's a different version of variable-length argument lists made specifically for C++?

EDIT: I have just realized, if you pass a pointer to a string (i.e. using the & prefix) it works well. All you have to do is dereference a string pointer in the custom sprintf, while passing the address of the std::string!

Still, it would be nice to see if there's any way to support string directly through variable-length argument lists. Thanks!

1 Answer 1

3

No -- as the compiler said, you're only allowed to pass objects of POD type to a variadic function.

What you normally want to do is eliminate using a variadic function in the first place, such as by using an iostream instead of something like printf (or a stringstream instead of sprintf).

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

13 Comments

Well, the reason I like sprintf is the way you can automatically convert ints/doubles into a string, and the nice format of using it. iostreams/stringstreams just seem clumsy to me when it's mixing many variables and spacers, i.e. "Hello %s, the time is %d:%d:%d, on the %dth day of the %dth month."
Have you looked at Boost format? boost.org/doc/libs/1_46_0/libs/format/index.html
@FurryHead: The simplest way to use a stringstream for trivial conversions is to use boost::lexical_cast; it is straightforward to implement and you can find the basic implementation in Herb Sutter's article, "The String Formatters of Manor Farm"
@FurryHead: I would say the streams version is easier to read and far, far easier to maintain as everything is inline.
@Johnsyweb: and then you get a French (me) who asks you to translates the text, and suddenly IOStreams are no longer convenient, at all.
|

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.