【问题标题】:c++ format cout with "right" and setw() for a string and floatc++ 用“right”格式化 cout 和 setw() 用于字符串和浮点数
【发布时间】:2018-12-03 07:52:14
【问题描述】:

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

Result       $ 34.45

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

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

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

对处理这种格式有什么建议吗?

【问题讨论】:

  • 稍作修改,您的代码将提供this。这还不够好吗?
  • "Result" 很长时,您的方法会导致奇怪的(IMO)输出。如果this example 不是您想要的,您应该添加您所期望的。

标签: c++ string setw


【解决方案1】:

您需要将 "$ " 和值 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 (overload 4)。

    【讨论】:

      【解决方案3】:

      另一种方法是使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        相关资源
        最近更新 更多