简体   繁体   中英

C to C++ printf

我如何更改此代码,并使用cout将格式保留为C ++?

  printf(" %5lu %3d %+1.2f ", nodes, depth, best_score / 100.0);

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);
#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);
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM