how do i line up my code

How do i make my output look like this:

Please enter the Quantity desired: 5
Please enter the Unit price: 10

The Quantity desired is : 5
The Unit Price is : $10
The Total Amount is : $50

(wont work in this so basically with the colons lined up)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
using namespace std;
int main() {
	// This program calulates the unit price.
	// Written by: Joe Vardaman

	int Quantity;
	int UnitPrice;
	int TotalAmount;
	cout << "Please enter the Quantity desired:";
	cin >> Quantity;
	cout << "Please enter the Unit Price:";
	cin >> UnitPrice;
	cout << "The Quantity desired is:"; cout << Quantity <<endl;
	cout << "The Unit Price is:"; cout << UnitPrice<<endl;
	TotalAmount = Quantity * UnitPrice;
	cout << "The Total amount is:"; cout << TotalAmount ;
	return 0;
}
Last edited on
How do i make my output look like this:
Please enter the Quantity desired: 5     
Please enter the Unit price: 10

The Quantity desired is : 5
The Unit Price is       : $10
The Total Amount is     : $50
The simplest way is to type the spaces in the program code itself:
1
2
3
    cout << "The Quantity desired is : "  << Quantity  << endl;
    cout << "The Unit Price is       : $" << UnitPrice << endl;
    cout << "The Total amount is     : $" << TotalAmount ;


You can use the #include <iomanip> header and setw(), but the code becomes a bit verbose. Or use string manipulaton functions as an alternative.
1
2
3
    cout << left << setw(25) << "The Quantity desired is" << right << ": " << Quantity << endl;
    cout << left << setw(25) << "The Unit Price is" << right << ": $" << UnitPrice << endl;
    cout << left << setw(25) << "The Total amount is" << right << ": $" << TotalAmount ;


You could write a short function to contain all that formatting code if you like.
1
2
3
4
void heading(string text)
{
    cout << left << setw(25) << text << right << ": ";    
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>//for stream manipulators
using std::cin; using std::cout; //avoid using std namespace;

int main() {
	// This program calulates the unit price.
	// Written by: Joe Vardaman

	int Quantity{}; // initialize variables upon declaration
	int UnitPrice{};


	cout << "Please enter the Quantity desired:";
	cin >> Quantity;

	cout << "Please enter the Unit Price:";
	cin >> UnitPrice;

	cout << std::setw(35) << "The Quantity desired is: ";
	cout << Quantity <<'\n';

	cout << std::setw(35) << "The Unit Price is: " << UnitPrice << '\n'; // don't need 2 separate cout's, can be chained;
	int TotalAmount = Quantity * UnitPrice;//declare variables where you need them;

	cout << std::setw(35) <<  "The Total amount is: " <<  TotalAmount << '\n';
	return 0;
}
Topic archived. No new replies allowed.