C на C ++ printf - PullRequest
       23

C на C ++ printf

2 голосов
/ 29 октября 2011

Как бы я изменил этот код, сохранив форматирование в C ++, используя cout?

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

Ответы [ 3 ]

5 голосов
/ 29 октября 2011

Если честно, мне никогда не нравился механизм форматирования ostream. Я обычно использую boost :: format , когда мне нужно сделать что-то подобное.

std::cout << boost::format(" %5lu %3d %+1.2f ") % nodes % depth % (best_score / 100.0);
1 голос
/ 29 октября 2011
#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);
}
0 голосов
/ 29 октября 2011

Используйте 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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...