Re: Using printf in C++
On 22/05/2012 21:56, jacob navia wrote:
Sure, then the boss says:
"I want rounding to 2 decimals, names flush left in the first
column that must be 16 chars long"
printf("%-16s|%10.2g|\n",name[i],value[i]);
And how would it look in C++ please?
In C++ it would look like:
cout << format << name << value << '\n';
The C++ way also gives you more flexibility: you can swap the columns by
just swapping the variables and without modifying the formatting
manipulator; or you can add as many columns as you want in the same
line, with any type (string or double). You can NOT do this via printf()
without also modifying the formatting string every time.
Here is a program showing what I have said:
#include <iostream>
#include <iomanip>
#include <cstdio>
template<class T> class OStreamWrapper {
public:
OStreamWrapper(T& stream) : m_stream(stream) { }
const OStreamWrapper& operator<<(const double v) const {
m_stream.precision(2);
m_stream << std::setw(10) << std::right << v << '|';
return *this;
}
const OStreamWrapper& operator<<(const char* s) const {
m_stream << std::setw(16) << std::left << s << '|';
return *this;
}
template<class U> // anything else terminates the formatting
T& operator<<(const U& u) const {
return m_stream << u;
}
private:
T& m_stream;
};
class Format {
};
template<class T>
inline OStreamWrapper<T> operator <<(T& stream, Format(*)()) {
return OStreamWrapper<T > (stream);
}
inline Format format() {
return Format();
}
int main() {
const char* name[2] = {"Hello", "World!"};
const double value[2] = {1.123, 123.123};
std::printf("%-16s|%10.2g|\n", name[0], value[0]); // C way
std::cout << format << name[0] << value[0] << '\n'; // C++ way
// You can add columns preserving the formatting
std::cout << format << name[0] << value[0] << name[1] << value[1]
<< '\n';
// ..or you can swap columns by swapping the variables
std::cout << format << value[0] << name[0] << '\n';
return 0;
}