Trying to format nice columns via cout

How can I make my app format nicely format columns. See program below.

#include <iostream>
#include <iomanip>

const double minFee = 2.00;
const double maxFee = 10.00;
const int maxCars = 3;

using namespace std;

double calculateCharge (double time);

int main (int argc, const char * argv[])
{

double time[maxCars] = {0};
double amt[maxCars] = {0};

for (int car = 0; car < maxCars; car++)
{
cout << "Car " << car+1 << ": Enter Time in Hours or 0 to exit " ;
cin >> time[car];
if (time <= 0)
{
return 0;
}

}

cout << "Car\t\tHours\tCharge" << endl;
double totalHours = 0;
double totalAmt = 0;

for (int car = 0; car < maxCars ; car++)
{
amt[car] = calculateCharge(time[car]);

cout << car << "\t\t" << fixed << setprecision(1) << time[car] <<"\t\t" << fixed << setprecision(2) << amt[car] << endl;
totalHours += time[car];
totalAmt += amt[car];
}
cout << "TOTAL\t" << setw << right << fixed << setprecision(1) << totalHours << "\t" << fixed << setprecision(2) << totalAmt << endl;
// printf ("Total\t%0.2f\t\t%0.2f\n",totalHours,totalAmt);
return 0;
}

double calculateCharge (double time)
{
double amt = 0;
double eps = 0.0001; // minimum time resolution

if (time <= 3.0)
{
return minFee;
}
if (time >= 24)
{
return maxFee;
}

time = time - eps;
int t2 = (int)(time - 3.0);
amt = minFee+ (t2+1)*0.50;

return amt;
}
I have an idea. Store what you want to "cout" into a string. That way, you can access its size. Then use that, with some spaces, to put your columns into place.
For example:
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
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
using namespace std;

//function to print certain number of spaces
void putspace(int spc){
    for (int i = 0; i<spc; i++){
        cout << " ";}}

//how far over we want our column to be
const int WIDTH = 50;

int main(){
    //output string
    string output = "row1";

    //insert output, then the number of spaces required to get to 100, then the column
    cout << output;
    putspace(WIDTH - output.size());
    cout << "Even column1" << endl;

    //change output
    output = "row2";

    //same
    cout << output;
    putspace(WIDTH - output.size());
    cout << "Even column2" << endl;

    /*
    whatever you prefer to stop the program
    people get REALLY aggressive over the "proper" way to do this, 
    so i will leave it blank
    */

    return 0;}
Last edited on
Topic archived. No new replies allowed.