I have been wondering if there is any alternative to printf in c++?
I find it very welcome that you can output text pretty fast and easy with it
printf("Hello, %d is the half of %d!\n", 2, 4);
instead of
cout << "Hello, " << 2 << " is the half of " << 4 << "!" << endl;
but unfortunately I do not think that printf is the way to go nowadays as you have to convert strings as example to c_str first, is there any other method that is able to output variables using % ?
printf works just fine in c++ programs for most simple things and can be cleaner, as you noted. cout is preferred for object oriented coding and pure c++, but printf IMHO is cleaner for printing loads of doubles or simple text and I use it when it seems useful. Extracting a char* from a string isn't that hard, but if you have a string already, cout << string << endl; done. Or cout << string1+string2<<endl; Printf shines for doubles, really, that setw stuff is garbage to me.
With the new variadic template features in C++ it should be possible to write safe alternatives for printf that works correctly with user defined types and that fails graciously if the format doesn't match the arguments. Someone might have written something like this already, but all I know is that it's not part of the standard library.
Someone might have written something like this already
It is in Stroustrup's book (The C++ Programming Language, 4th Ed) - and you are absolutely right @Peter87 - it is the precise example he uses to introduce variadic templates.
I'm trying to make a variadic template print function with fold expression but the arguments are printed without space or newline characters - any suggestions?:
cubbi - the problem persists and reading up online I came across this from cire that seems to be the issue:
The fold expression with a binary operator is just meant to be a chain of those operators separating the arguments with nothing intervening (with an initial or trailing value.)