user975900
user975900

Reputation: 77

C to C++ printf

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

Answers (3)

Mooing Duck
Mooing Duck

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

Bill Lynch
Bill Lynch

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

Scott Taylor
Scott Taylor

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

Related Questions