2011-10-28 43 views
2

我將如何更改此代碼,使用cout保留格式爲C++?C到C++ printf

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

9個問​​題,您還沒有接受過單個答案?我們爲什麼要麻煩幫你? – 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'。 chainables以'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

爲什麼你使用'setprecision'作爲深度而不是'setw'? – Shahbaz

+0

@Shahbaz:無法正確理解printf標誌:(我剛注意到我也忽略了best_score上的標誌標誌。 –

5

說實話,我從來都不喜歡ostream的格式化機制。當我需要做這樣的事情時,我傾向於使用boost::format

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