2011-10-28 13 views
2

coutを使用してC++への書式設定を保持して、このコードをどのように変更できますか?C to C++ printf

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

9個の質問があり、あなたは1つの回答を受け入れていませんか?なぜ私たちはあなたを手伝ってくれませんか? – abelenky

+4

あなたはそれを絶対に変更する必要はありませんか? –

+1

変換のどの部分に問題がありますか? printfコンポーネントの意味を理解していますか?私は、この特定の質問に対する答えに誰も気にしないので、これを「ローカライズすぎる」と締めくくりました。 printf文字列の小さな部分をどのように変換するかなどを尋ねるなど、より一般的なものにするために、それを言い換えてください。たとえば、 '+'記号を指摘し、代わりにiostream形式の書式を使用して数字記号を強制する方法を尋ねることができます。 –

答えて

0

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; 
+1

チェインの 'width'-' 'setw'と' precision'-> 'setprecision'です。連鎖可能物は 'set'で始まり、メンバーは' set'で始まらない。 –

1
#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

出力後にフォーマット設定をデフォルトにリセットするのはどうですか? –

+0

なぜ 'setw'ではなく' depth 'に 'setprecision'を使用していますか? – Shahbaz

+0

@Shahbaz:printfフラグを正しく理解できませんでした:(私はbest_scoreのsignフラグも無視しています。 –

5

正直に言うと、私はメカニズムをフォーマットのostreamを言っていたことがありません。私はこのようなことをする必要があるときにboost::formatを使う傾向がありました。

std::cout << boost::format(" %5lu %3d %+1.2f ") % nodes % depth % (best_score/100.0);