Having issues with output formatting

Thanks for checking this out for me. So my issue is when formatiing my cout streams for some example programs I'm writing for class.If I need to use different prefix' or a suffix' (like a $, or .lb) it doesn't print out to the screen lined up. In the code I posted, the dollar amount looks tabbed in further than it should.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
double weight, distance;

cout << "input weight in kilograms.\n";
cin >> weight;
cout << "input how far in miles\n";
cin >> distance;

cout << setprecision(2) << fixed;
 
cout << "Package Weight  " <<setw(8) << weight <<"kg" << endl;
cout << "Distance to Ship" <<setw(8) << distance <<" miles" << endl;
cout << "Cost to Ship    "  <<setw(8) << "$" <<distance*2.2 << endl;

return 0;
}
Last edited on
setw() function doesn't work properly all the times and I am not sure why. But I'd just play around with the numbers to fix the output format. So for example for cost to ship, if you change setw from setw(8) to setw(4) then it prints properly.
You might use a stringstream to add the '$' to the front of the number. Then the setw(8) will apply to the entire thing, instead of just to the '$' alone.

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
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

using namespace std;

string addPrefix(string prefix, double value)
{
    ostringstream os;
    os << fixed << setprecision(2);
    os << prefix << value;
    return os.str();
}

int main()
{
    double weight, distance;

    cout << "input weight in kilograms.\n";
    cin  >> weight;
    cout << "input how far in miles\n";
    cin  >> distance;

    cout << setprecision(2) << fixed;
     
    cout << "Package Weight  " << setw(8) << weight << "kg" << endl;
    cout << "Distance to Ship" << setw(8) << distance <<" miles" << endl;
    cout << "Cost to Ship    " << setw(8) << addPrefix("$", distance*2.2) << endl;

    return 0;
}


Output:
input weight in kilograms.
12
input how far in miles
34
Package Weight     12.00kg
Distance to Ship   34.00 miles
Cost to Ship      $74.80

Last edited on
Thanks Chevril, thats perfect. And thanks for helping out a rookie!
Topic archived. No new replies allowed.