Helpful Information
 
 
Category: C Programming
Formatting Help

I have this program and I need to know how to format it correctly:

#include <iostream.h>
#include <math.h>
#include <iomanip.h>

void main(void)
{

double Principle = 0.0;
double Interest = 0.0;
double Savings = 0.0;
float InterestR = 0.0f;
int T = 0;

cout << "Savings Account" << endl << endl;

cout << "Please enter in the principle: ";
cin >> Principle;

cout << "Please enter in the interest rate: ";
cin >> InterestR;
InterestR = InterestR/100;

cout << "Please enter in the number of times compounded during a year: ";
cin >> T;

Savings = Principle * pow((1 + (InterestR / T)),T);
Interest = Savings - Principle;

cout << setprecision(2) << setiosflags(ios::fixed | ios::showpoint);

//Formatted text needs to go here

}

This is what the output should look like:

Interest Rate: 4.25%
Times Compounded: 12
Principle: $ 1000.00
Interest: $ 43.33
Amount in Savings: $ 1043.33

Another Example would be:

Interest Rate: 50%
Times Compounded: 12
Principle: $ 10000.00
Interest: $ 6320.94
Amount in Savings: $ 16320.94

I need the numbers to line up correctly each time, no matter how big the numbers are. I need the last number on the right of each number to line up. So basically it needs to be right aligned.

Thanks,
Jonathan Donaghe

If you calculate the number of characters you'll be printing, you can use the cout.width() member. The cout.width() member function will automatically fill the blank area with whitespace to right align the next output with the width you specify. You can change the fill character with cout.fill(), I believe.



// Just assign the character arrays for now
// for simplicity.
char chInt[] = "Interest Rate:";
char chIntRate[] = "4.56%";
char chPrinc[] = "Principle:";
char chPrinciple[] = "$9 876.54";

// bring into namespace
using std::cout;
using std::endl;

// print out the formatted results
cout << chInt;
cout.width(40 - sizeof(chInt));
cout << chIntRate << endl;
cout << chPrinc;
cout.width(40 - sizeof(chPrinc));
cout << chPrinciple << endl;

return 0;

You can use setw(length) too, if you wanted.


cout << setw(10) << "Text";










privacy (GDPR)