2014-01-21 49 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();