使用C++的cout格式化输出,结合"right"和setw()函数对字符串和浮点数进行格式化。

4
我正在尝试格式化一个'cout',它必须显示类似于这样的内容:
Result       $ 34.45

金额($34.45)必须在正确的位置并包含一定量的填充,或者以特定的列位置结束。我尝试使用了


cout << "Result" << setw(15) << right << "$ " << 34.45" << endl;

然而,它是为“$”字符串设置宽度,而不是字符串加上金额的宽度。
有关如何处理这种格式的建议吗?

经过轻微的修改,您的代码生成了这个。这不已经足够好了吗? - gsamaras
你的方法在 "Result" 很长的情况下会产生奇怪(我认为)的输出。如果 这个例子 不是你想要的结果,你应该添加你期望的内容。 - apple apple
3个回答

3
您需要将"$ "和值34.45组合成单独的字符串。可以尝试如下方法:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int main()
{
    stringstream ss;
    ss << "$ " << 34.45;

    cout << "Result" << setw(15) << right << ss.str() << endl;
}

2

您试图对两个不同类型的参数(字符串文字和double)应用格式修饰符,这是行不通的。要为"$ "和数字都设置宽度,您需要先将它们都转换为字符串。一种方法是:

 std::ostringstream os;
 os << "$ " << 34.45;
 const std::string moneyStr = os.str();

 std::cout << "Result" << std::setw(15) << std::right << moneyStr << "\n";

这段话有点啰嗦,你可以将前半部分放在一个辅助函数中。此外,std::ostringstream的格式化可能不是最佳选择,你还可以看看std::snprintf(重载4)。


0
一个替代方案是使用 std::put_money
#include <iostream>
#include <locale>
#include <iomanip>

void disp_money(double money) {
    std::cout << std::setw(15) << std::showbase << std::put_money(money*100.)<< "\n";
}

int main() {
    std::cout.imbue(std::locale("en_US.UTF-8"));
    disp_money(12345678.9);
    disp_money(12.23);
    disp_money(120.23);
}

输出

 $12,345,678.90
         $12.23
        $120.23

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接