gpt4 book ai didi

c++ format cout with "right"and setw() for a string and float

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:44 25 4
gpt4 key购买 nike

我正在尝试格式化一个“cout”,它必须显示如下内容:

Result       $ 34.45

金额 ($34.45) 必须在右侧索引上,并带有一定数量的填充或在特定列位置结束。我尝试使用

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

但是,它是为“$”字符串设置宽度,而不是为字符串加金额设置宽度。

关于处理此类格式有什么建议吗?

最佳答案

您需要将 "$ " 和值 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;
}

关于c++ format cout with "right"and setw() for a string and float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53589535/

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