參見:Which C I/O library should be used in C++ code?
struct Item
{
std::string artist;
std::string c;
integer price; // in cents (as floating point is not acurate)
std::string Genre;
integer disc;
integer sale;
integer tax;
};
std::cout << "Sales Report for September 15, 2010\n"
<< "Artist Title Price Genre Disc Sale Tax Cash\n";
FOREACH(Item loop,data)
{
fprintf(stdout,"%8s%8s%8.2f%7s%1s%8.2f%8.2f\n",
, loop.artist
, loop.title
, loop.price/100.0
, loop.Genre
, loop.disc , "%"
, loop.sale/100.0
, loop.tax/100.0);
// or
std::cout << std::setw(8) << loop.artist
<< std::setw(8) << loop.title
<< std::setw(8) << fixed << setprecision(2) << loop.price/100.0
<< std::setw(8) << loop.Genre
<< std::setw(7) << loop.disc << std::setw(1) << "%"
<< std::setw(8) << fixed << setprecision(2) << loop.sale/100.0
<< std::setw(8) << fixed << setprecision(2) << loop.tax/100.0
<< "\n";
// or
std::cout << boost::format("%8s%8s%8.2f%7s%1s%8.2f%8.2f\n")
% loop.artist
% loop.title
% loop.price/100.0
% loop.Genre
% loop.disc % "%"
% loop.sale/100.0
% loop.tax/100.0;
}
下面的回答允許指定列的寬度。請注意,這需要您知道上限(例如數據庫約束)或預先計算(這可能意味着在實際開始打印之前解析整個結構)。第二個,雖然有必要,但當然要慢:) –