[英]C to C++ printf
我如何更改此代码,并使用cout将格式保留为C ++?
printf(" %5lu %3d %+1.2f ", nodes, depth, best_score / 100.0);
老实说,我从未喜欢过ostream格式化机制。 当我需要做这样的事情时,我倾向于使用boost :: format 。
std::cout << boost::format(" %5lu %3d %+1.2f ") % nodes % depth % (best_score / 100.0);
#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);
}
使用cout.width(n)和cout.precision(n);
因此,例如:
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;
您可以将事物链接在一起:
cout << width(5) << nodes << " " << width(3) << depth << " "
<< setiosflags(ios::fixed) << precision(2) << best_score/100.0 << " "
<< endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.