2016-09-18 65 views
1

我有一些問題產生這個輸出爲我的代碼。iomanip格式化多輸入和美元符號 - C++

Apples 
10 @ 0.98/UNIT:         $9.80 
Bananas 
1 @ 1.29/UNIT:         $1.29 
Flank Steak 
1 @ 8.82/UNIT:         $8.82 
Chocolate Ice Cream 
1 @ 3.23/UNIT:         $3.23 
Gym Bag 
1 @ 23.12/UNIT:         $23.12 
ORDER TOTAL:************************************$46.26 

我的問題是與附加美元符號的總計的小數位數對齊。我應該可以用原始setw()代碼和右側,左側對齊方式來做到這一點,但我不確定如何在$和實際數值之間沒有空格的情況下繼續。

這裏是我到目前爲止得到了..

void printReceipt(const int cart[], const string productName[], const double prices[], int productCount){ 
    double orderTotal = 0; 
    for (int i = 0; i < productCount; i++){ //Loop for output of receipt 
     if (cart[i] != 0){    //Will not output for item not ordered. 
     cout << productName[i] << endl; 
     cout << fixed << setprecision(2) 
     << setw(3) << left << cart[i] 
     << setw(3) << " @ "          //Formatting for receipt print 
     << setw(6) << prices[i] 
     << setw(35) << left << "/UNIT:" << "$" 
     << setw(6)<< right << (cart[i] * prices[i]) << endl; 
     orderTotal = orderTotal + (cart[i] * prices[i]); 
    }} 
    cout << fixed << setfill('*') << setw(47)<< left << "ORDER TOTAL:";   
    cout << setfill(' ') << "$" << setw(6) << right << setprecision(2) << orderTotal; 
} 

電流輸出如下

Apples 
5 @ 0.98/UNIT:        $ 4.90 
Bananas 
5 @ 1.29/UNIT:        $ 6.45 
Flank Steak 
5 @ 8.82/UNIT:        $ 44.10 
Chocolate Ice Cream 
5 @ 3.23/UNIT:        $ 16.15 
Gym Bag 
5 @ 23.12/UNIT:        $115.60 
ORDER TOTAL:***********************************$187.20 

回答

0

你將不得不這樣做,因爲一兩個步驟的過程。

  1. 格式的美元金額(cart[i]*prices[i])成std::ostringstream,僅使用setprecision操縱器。沒有最低setw,所以你得到的是格式化的數額。從std::ostringstream獲取字符串表示,使用str()

  2. 通過使用從str()返回的字符串的長度,可以計算定位'$'所需的填充量。

而不是固定的setw(35),你將計算該字段的填充。正如一個粗略的估計,這將可能是:

<< setw(42-amount.length()) << left << "/UNIT:" << "$" << amount << std::endl; 

其中amount被格式化的std::string你在步驟1中得到這樣,這裏的寬度會自動調整給的房間適量的amount

這本身不會調整在行首的單位數量,這也是可變長度。但是,在正確處理amount之後,您應該能夠找出如何以相同的方式解決這個問題。