4

I am trying to format a 'cout' where it has to display something like this:

Result       $ 34.45

The amount ($ 34.45) has to be on right index with certain amount of padding or end at certain column position. I tried using

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

However, it's setting the width for the "$ " string, not for the string plus amount.

Any advice on dealing with such formatting?

ozn
  • 1,990
  • 3
  • 26
  • 37
  • With minor modifications, your code gives [this](https://wandbox.org/permlink/mqpuQZJrgfonXeX7). Isn't that already good enough? – gsamaras Dec 03 '18 at 07:56
  • your method would result in strange(IMO) output when `"Result"` is long. you should add what you expected if [this example](https://wandbox.org/permlink/N5DeVo6jfO6C4vF7) is not what you want. – apple apple Dec 03 '18 at 08:16

3 Answers3

3

You need to combine "$ " and value 34.45 into separate string. Try like this:

#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;
}
snake_style
  • 1,139
  • 7
  • 16
2

You try to apply a format modifier to two arguments of different types (string literal and a double), which can't work out. To set a width for both the "$ " and the number, you need to convert both to a string first. One way would be

 std::ostringstream os;
 os << "$ " << 34.45;
 const std::string moneyStr = os.str();

 std::cout << "Result" << std::setw(15) << std::right << moneyStr << "\n";

This is admittedly verbose, so you may put the first part in a helper function. Also, std::ostringstream formatting might not be the best choice, you can also have a look at std::snprintf (overload 4).

lubgr
  • 37,368
  • 3
  • 66
  • 117
0

An alternative could be to use 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);
}

Output

 $12,345,678.90
         $12.23
        $120.23
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108