Search code examples
c++stringsetw

c++ format cout with "right" and setw() for a string and float


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?


Solution

  • 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;
    }