2014-01-21 44 views
0

我通過一個持續的循環,我想我的輸出是這個樣子:格式化C++有一個for循環

apples_fuji  18.93 31.99 
apples_gala  25.34 27.62 
apples_jazz  16.77 36.73 
apricots   17.92 22.22 
bananas   25.87 18.63 
cherries   16.30 78.40 
grapes_red  15.62 41.86 
grapes_white  23.06 86.94 
pears_anjou  26.35 28.72 
pears_bosc  12.03 15.52 
plantains  16.35 23.54 
watermelon  14.33 32.82 

totals   228.87 444.99 

不幸的是,它看起來像這樣

apples_fuji   18.93 31.9917 
apples_gala   25.34 27.6206 
apples_jazz   16.77 36.7263 
apricots   17.92 22.2208 
bananas   25.87 18.6264 
cherries   16.3 78.403 
grapes_red   15.62 41.8616 
grapes_white   23.06 86.9362 
pears_anjou   26.35 28.7215 
pears_bosc   12.03 15.5187 
plantains   16.35 23.544 
watermelon   14.33 32.8157 
totals 228.87 444.987 

,其中第一col是所有字符串,其次是整數。什麼是格式化最好或最簡單的方法?我有一些麻煩,因爲字符串的長度不同

int num; 
int total_amount, tote_amount, tote_price; 

for (int i=0; i < num; i++) 
    cout << string "  " << num1 << " " << num2 <<endl; 

cout << "totals"< < " " << tote_amount << " " << tote_price <<endl; 
+1

也許標籤將有助於 「\ t」 的;也修復for循環中的行。 'string'「' – Gasim

+0

[setw](http://en.cppreference.com/w/cpp/io/manip/setw)就是你需要的。 – Borgleader

+0

查看流修飾符:精度,寬度和填充。搜索「std :: precision」的stackOverflow。 –

回答

4

如果你的字符串有一個最大的lenght,您可以使用

std::cout << std::setw(max_length) << std::setfill(' ') << left << value << ... 
1

如果你的字符串有一個最大的lenght,您可以使用
的std :: COUT < <的std ::運輸及工務局局長(MAX_LENGTH)< <的std :: setfill(」「)< <左< <值< < ...

如果你不知道的最大長度,你可以之前(在C++ 11)做這樣的事情:

int maxLength = std::max_element(begin(names), end(names), 
           [](std::string const & a, std::string const & b) { return a.length() < b.length(); })->length();