I'm just now seeing another naive C++ code using sprintf to append C builtins into an array of chars, and I guess enough is enough.
I could help providing with simple, lightweight, appending and non-formatting functions for std::string, but as it would be check-in-ed into the team's common code, I want it to be perfect, so I need some advice on the interface of this feature (i.e. not on the actual implementation).
The following could be possible (I did not test it, it's just a hunch):
+=" operator (probably in another namespace than std or global)<<" operator (again, in another namespace)What would be the pros and the cons of each solution (I have a preference for "+=", or even "<<") ?
using namespace SomeNamespace ; as its done for the <utility>'s rel_ops namespace)std::string which is not able, natively, to handle other types than itself, char and char *. I want to extend that to handle other simple types..str() to put it inside a string, etc. etc.), and the last thing I want is an syntactic sugared inline function instanciating a stringstream at each call). As you can see in the example below, the stringstream solution is too verbose:.
// sprintf-like code with a char[] buffer:
sprintf(buffer, "%d", myDouble) ;
// stream-like code with a std::string buffer:
std::stringstream str ;
str << myDouble ;
buffer = str.str() ;
// example of desired code with a std::string buffer:
buffer += myDouble ;
I would use ostringstream and stream manipulators to replace sprintf. It's not worth reinventing the wheel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With