Reputation: 77
How would I change this code, preserving formatting to C++ using cout?
printf(" %5lu %3d %+1.2f ", nodes, depth, best_score / 100.0);
Upvotes: 2
Views: 1252
Reputation: 66981
#include <iostream>
#include <iomanip>
void func(unsigned long nodes, int depth, float best_score) {
//store old format
streamsize pre = std::cout.precision();
ios_base::fmtflags flags = std::cout.flags();
std::cout << setw(5) << nodes << setw(3) << depth;
std::cout << showpos << setw(4) << setprecision(2) << showpos (best_score/100.);
//restore old format
std::cout.precision(pre);
std::cout.flags(flags);
}
Upvotes: 1
Reputation: 82006
To be honest, I've never liked the ostream formatting mechanism. I've tended to use boost::format when I need to do something like this.
std::cout << boost::format(" %5lu %3d %+1.2f ") % nodes % depth % (best_score / 100.0);
Upvotes: 5
Reputation: 1
Use cout.width(n) and cout.precision(n);
So, for example:
cout.width(5);
cout << nodes << " ";
cout.width(3);
cout << depth << " ";
cout.setiosflags(ios::fixed);
cout.precision(2);
cout.width(4);
cout << best_score/100.0 << " " << endl;
You can chain things together:
cout << width(5) << nodes << " " << width(3) << depth << " "
<< setiosflags(ios::fixed) << precision(2) << best_score/100.0 << " "
<< endl;
Upvotes: 0