gpt4 book ai didi

c++ - 多个输入和美元符号的 iomanip 格式 - C++

转载 作者:太空宇宙 更新时间:2023-11-04 13:11:37 24 4
gpt4 key购买 nike

我在为我的代码生成此输出时遇到了一些问题。

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

最佳答案

您必须分两步执行此操作。

  1. 将美元金额 (cart[i]*prices[i]) 格式化为 std::ostringstream,仅使用 setprecision 操纵器。没有最小 setw,所以您得到的只是格式化的数量。使用 str()std::ostringstream 获取字符串表示形式。

  2. 通过使用从 str() 返回的字符串的长度,您可以计算定位“$”所需的填充量。

您将计算此字段的填充,而不是固定的 setw(35)。作为粗略估计,这可能是:

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

其中amount是你在第一步中得到的格式化后的std::string。这样的话,这里的宽度会自动调整,给适当的空间金额

这本身不会调整行首的单位计数,这也是可变长度。但是在正确处理了 amount 之后,在这里,您应该能够弄清楚如何以相同的方式解决这个问题。

关于c++ - 多个输入和美元符号的 iomanip 格式 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com