【问题标题】:How do I use setw in C++ to align/format text in the console如何在 C++ 中使用 setw 在控制台中对齐/格式化文本
【发布时间】:2019-02-17 22:57:18
【问题描述】:

我在尝试正确格式化我的代码外观时遇到问题。对不起,如果这是一个愚蠢的问题,但我对这一切真的很陌生。

我这里有这个sn-p:

cout << "Thank you for your business!\n";
cout << endl << endl << endl;
cout << fixed;
cout << setprecision(2);
cout << "Sub-total:" << setw(11)   << "$" << SubTotal << endl;
cout << "+Sales Tax:" << setw(12)  << "$" << SalesTax << endl;
cout << "-Discount:" << setw(13)   << "$" << Discount << endl;
cout << "+Shipping:" << setw(13)   << "$" << ShippingCost << " (shipping to " << Destination << ")" << endl;
cout << "=Total:" << setw(14)      << "$" << Total << endl;

所以我想要做的是让它输出,所以它看起来像这样:

注意所有 $ 符号和小数点是如何排列的。我有点迷路,我真的不知道该怎么做,所以我希望有人能指出我正确的方向。我只知道可以使用以下命令来完成:

setprecision
fixed
setw

我以为我可以在编辑器中将它排列起来,但是当我输入不同的数字时,它就会变得不均匀。

【问题讨论】:

    标签: c++


    【解决方案1】:

    给你:

    cout << "Thank you for your business!\n";
    cout << endl << endl << endl;
    cout << fixed;
    cout << setprecision(2);
    cout << setw(13) << left << "Sub-total:" << "$" << setw(8) << right << SubTotal << endl;
    cout << setw(13) << left << "+Sales Tax:" << "$" << setw(8) << right << SalesTax << endl;
    cout << setw(13) << left << "-Discount:" << "$" << setw(8) << right << Discount << endl;
    cout << setw(13) << left << "+Shipping:" << "$" << setw(8) << right << ShippingCost << " (shipping to " << Destination << ")" << endl;
    cout << setw(13) << left << "=Total:" << "$" << setw(8) << right << Total << endl;
    

    您的代码的问题在于您设置了“$”的宽度。 setw() 函数直接在它之后设置元素的宽度,在你的例子中是“$”。此外,它默认为右对齐方式,所以你给“$”这些可变长度,然后将字符推到你给它的空间的最右边。您可以看出,如果您将您的代码更改为统一编号的所有setw(),例如setw(10),您会注意到“:”字符和“$”之间的空格数” 每行正好是 9。您想要的是直接在“$”之前 的特定宽度。幸运的是,我们将调用第一个元素的“$”之前有文本,因此我们可以使用 setw() 函数将其设置为永久字符数。

    这样,我的解决方案设置了第一个元素的宽度。这样它们总是在同一个地方结束,并且保证下一个字符(“$”)出现在为第一个元素保留的空间之后。第二个setw() 有点难以识别。但是,如果您查看图像示例,您会注意到它实际上是具有永久宽度的数字,因此只需计算最大数字的字符数并将所有数字的宽度设置为此,当然,“$”和较小长度的数字之间有空格,提示右对齐。

    【讨论】:

      【解决方案2】:

      我想我会创建一个小类(或结构)来保存输出中的每个项目,并处理项目的格式:

      struct item { 
          std::string label;
          double amount;
          std::string note;
      
          friend std::ostream &operator<<(std::ostream &os, item const &i) { 
              os << std::setprecision(2) << std::fixed;
              os << std::setw(15) << std::left << i.label 
                 << " $" << std::right << std::setw(8) << i.amount;
              if (!i.note.empty())
                  os << " (" << i.note << ")";
              return os;
          }
      };
      

      有了这些,只需按照正确的顺序创建项目,然后将它们写出来:

      std::vector<item> items {
          { "Sub-total:", 17530},
          { "+ Sales Tax:", 1139},
          { "- Discount:", 25},
          { "+ Shipping:", 0, "Ship to: NJ"},
          { "= Total:", 18644.44}
      };
      
       for (auto const & i : items) 
           std::cout << i << "\n";
      

      然而,实际上,您通常会从一些实际物品(客户购买的东西)开始,所有这些物品都是从客户购买的东西中计算出来的:

      class sale {
          std::vector<item> items;
          const double tax_rate;
      public:
      
          sale(std::initializer_list<item> const& i, double tax_rate = 0.065) 
              : items(i)
              , tax_rate(tax_rate) 
          {}
      
          friend std::ostream& operator<<(std::ostream& os, sale const& s) {
              item subtotal{ "Subtotal:", 0 };
              item discount{ "- Discount: ", 0 };
              item sales_tax{ "+ Sales Tax:", 0 };
              item shipping{ "+ Shipping:", 0, 0, "Shipping to: NJ" };
              item total{ "= Total:", 0 };
      
              for (auto const& i : s.items) {
                  os << i << "\n";
                  subtotal.amount += i.amount;
                  discount.amount += i.discount;
                  shipping.amount += i.shipping;
                  total.amount += i.amount;
                  total.amount -= i.discount;
                  total.amount += i.shipping;
              }
              sales_tax.amount = subtotal.amount * s.tax_rate;
      
              os << std::string(40, '-') << '\n';
              os << subtotal << '\n';
              os << sales_tax << '\n';
              os << discount << '\n';
              os << shipping << '\n';
              os << total << '\n';
              return os;
          }
      };
      

      这样,我们只需列出他们购买的商品,它就会计算小计、税金等。

      int main() { 
          sale items {
              {"Kia Rio", 15390.00, 25},
              {"Stereo", 135.95},
              {"Undercoating", 249.95},
              {"Mud flaps", 124.99},
              { "ADP", 375.25}
          };
      
          std::cout << items << "\n";
      }
      

      ...产生类似这样的输出:

      Kia Rio         $15390.00
      Stereo          $  135.95
      Undercoating    $  249.95
      Mud flaps       $  124.99
      ADP             $  375.25
      ------------------------------
      Subtotal:       $16276.14
      + Sales Tax:    $ 1057.95
      - Discount:     $   25.00
      + Shipping:     $    0.00 (Shipping to: NJ)
      = Total:        $16251.14
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        • 2016-01-28
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2018-07-21
        相关资源
        最近更新 更多