Print Pretty in C++ hackerrank solution

Problem statement:

You need to format a given integer as a monetary value with currency symbol and precision.

The integer represents a given amount of money in dollars. You need to format it according to the given requirements.

      

Sample Input:

The input consists of a single integer n representing the amount of money.
123456789
      

Sample Output:

Print the formatted amount of money with currency symbol and precision.
$123,456,789.00

Explanation:

In this example, we have three queries:

The input integer is 123456789. The expected output is the formatted amount of money with a dollar sign, commas for thousands separator, and two decimal places precision.

      
  #include <iostream>
  #include <iomanip> 
  using namespace std;
  
  int main() {
      int n;
      cin >> n;
  
      cout << fixed << setprecision(2);
      cout << "$" << setw(9) << setfill('0') << n << endl;
  
      return 0;
  }
    

Code Explanation


We include the necessary header files, including for input/output operations and for formatting output.

In the main() function, we declare an integer variable n to store the input amount of money and read it from the user using cin.

To format the output, we set the output stream to fixed-point notation with two decimal places precision using cout << fixed << setprecision(2).

We then output the dollar sign symbol "$" using cout << "$".

To format the amount with leading zeros and commas, we use setw(9) to set the width of the output to 9 characters and setfill('0') to fill any remaining spaces with zeros.

Finally, we output the value of n using cout << n and end the line with endl.

The solution uses the fixed, setprecision, setw, and setfill manipulators from the library to format the output according to the given requirements.

I hope this solution meets your requirements and provides a clear understanding of the problem and its solution!