[英]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.