1

在过去的 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;

我真的很感激一些帮助。

4

3 回答 3

2

setw字段宽度是为下一个要输出的项目定义的,然后重置为0 。这就是为什么只有文本显示在 25 个字符上,而不是行上的剩余输出。

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

在这里您可以获得预期的结果

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

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

于 2016-02-15T23:42:21.143 回答
1

这是现场演示,它应该准确地输出您想要的内容。没有办法用 来设置精度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;
于 2016-02-15T23:30:37.427 回答
-1

如果你想

贷款金额:$ 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;
于 2016-02-15T23:40:36.890 回答