0

Hi,

Let's say x=12.34, y=567.89, z=6.38, and we want the output this way:

_____$12.34
____$567.89
______$6.38

right-aligned with the decimal point lined up (where the ___ are spaces)

In other words, all the numbers are right-aligned and immediately following "$". How to do that if you don't know what values x, y, z will have?

Is "... << right << setw(..) << ..." the way to go? But obviously the following won't work:

cout << right << setw(10) << "$" << x;
cout << right << setw(10) << "$" << y;
cout << right << setw(10) << "$" << y;

because that gives
_____$12.34
_____$567.89
_____$6.38

(keep in mind you can't adjust setw(9) or setw(8) accordingly because you don't know beforehand what values the variables will take)
Again, thanks in advance for any help! This forum is awesome!

2
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by sgw
0

this is one way to do it.

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
  std::ostringstream stm ;
  stm << '$' << std::fixed << std::setprecision(2) << 123.4567 ;
  std::cout << std::setw(11) << std::setfill(' ') << std::right 
            << stm.str() << '\n' ;
}
0

Thanks for the info. I'm not sure how to use this to align all x, y, z in the way I showed above. Is there a simpler way? Thanks again.

0
#include <iostream>
#include <sstream>
#include <iomanip>

enum { PRECISION = 2, WIDTH = 11, FILLER = ' ' } ;
inline void print_aligned( double value )
{
  // put $ddd.dd into a string
  std::ostringstream stm ;
  stm << '$' << std::fixed << std::setprecision(PRECISION) 
       << value ;
  // print the string in a right justified field
  std::cout << std::setw(WIDTH) << std::setfill( char(FILLER) )
            << std::right << stm.str() << '\n' ;
}

int main()
{
  double x=12.34, y=567.894, z=6.38215 ;
  print_aligned(x) ;
  print_aligned(y) ;
  print_aligned(z) ;
}
0

It works! vijayan121, thank you so much for your help!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.