【问题标题】:Another C++ output alignment issue另一个 C++ 输出对齐问题
【发布时间】:2016-02-15 23:19:48
【问题描述】:

在过去的 3 个小时里,我一直在尝试将以下代码对齐,但成功率为零。有人可以告诉我我做错了什么吗? 我的目标是让字符串文字左对齐,变量右对齐,如下所示:

Loan amount:             $ 10000.00
Monthly Interest Rate:        0.10%

但这是我一直得到的:

Loan amount:             $ 10000.00
Monthly Interest Rate:   0.10%

这是我一直在尝试的最新版本:

cout << setw(25) << "Loan amount:" << right << "$ "<< amount << endl;
cout << setw(25) << "Monthly Interest Rate:"<< right<< rateMonthly << "%" << endl;

非常感谢您的帮助。

【问题讨论】:

  • right 无效,除非与 setw 一起使用,例如&lt;&lt; right &lt;&lt; setw(10) &lt;&lt; rateMonthly.
  • 如其他答案所示(虽然没有解释原因),right 是“粘性”;所以你需要为下一行再次设置left。事实上,除了setw之外,所有的操纵器都是粘性的。
  • 如果您要处理需要左右对齐的更复杂的格式,您可能需要编写自己的函数来执行此操作,该函数接受左字符串和右字符串以及宽度作为参数

标签: c++ cout text-align iomanip setw


【解决方案1】:

setw 字段宽度是为next item to be output and is reset to 0 afterwards 定义的。这就是为什么只有文本显示在 25 个字符上,而不是行上的剩余输出。

rightleft 对齐符定义填充字符在字段中的放置位置。这意味着它仅适用于当前字段,如果它具有定义的宽度。这就是为什么该理由不适用于正文后面的项目。

在这里获取expected result

cout <<setw(25)<< left<< "Loan amount:" <<  "$ "<< setw(10)<<right << amount << endl;
cout <<setw(25)<< left << "Monthly Interest Rate:"<<"  "<<setw(10)<<right<< rateMonthly << " %" << endl; 

如果您希望 $ 位于数字旁边,则必须确保将 $ 和数字连接成一个对象以输出,方法是将它们放在一个字符串中,或​​者使用货币格式.

【讨论】:

  • 哇,谢谢!就像我提到的,我已经尝试了一段时间,我尝试分别为一行指定 setw() 和左右两次,但我不知道它只适用于下一项。我猜 $ 和 % 符号弄乱了输出。我猜你每天都会学到一些东西。再次感谢你。 :)
【解决方案2】:

这是live demo,它应该准确地输出您想要的内容。 无法使用std::to_string(double) 设置精度,因此我创建了一个小助手来执行此操作。

auto to_string_precision(double amount, int precision)
{
    stringstream stream;
    stream << fixed << setprecision(precision) << amount;
    return stream.str();
};

cout << setw(25) << left << "Loan amount:" << setw(10) << right << ("$ " + to_string_precision(amount, 2)) << endl;
cout << setw(25) << left << "Monthly Interest Rate:" << setw(10) << right << (to_string_precision(rateMonthly, 2) + "%") << endl;

另类,我还是觉得这个更好看:

cout << setw(25) << left << "Loan amount:" << "$ " << amount << endl;
cout << setw(25) << left << "Monthly Interest Rate:" << rateMonthly << "%" << endl;

【讨论】:

  • 我认为他正在寻找金额的最后一位数字与下一行的%对齐
【解决方案3】:

如果你愿意

贷款金额:$ 10000.00 月利率:0.10%

如果你不想打扰左右,你可以使用

cout  << "Loan amount:"  <<setw(25)<< "$ "<< amount << endl;
cout  << "Monthly Interest Rate:"<< setw(19)<< rateMonthly << "%" << endl;

你可以使用下面的

cout << setw(25) << left << "Loan amount:"<< "$ " << amount << endl;
cout << setw(28) << left << "Monthly Interest Rate:" << rateMonthly << "%" <<endl;

【讨论】:

    猜你喜欢
    • 2012-12-25
    • 2018-01-31
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多