0

I'm trying to make a receipt, andbalways want the " kg" to be ONE SPACE after the weight, and also "$" just before both 'costperkg' and 'totacost' Initially using setw to format the output, could not get it to work, got it done with ostringstream. I Can anyone explain why does pushing double quote string does not work?

This one does not work :

int main()
{
string item = "A" ;
double weight = 2.00 ;
double costperkg = 1.98 ;
double totalcost = 3.96 ;

cout << fixed << showpoint << setprecision(2);

cout << setw(14) << left << "ITEM" << setw(16) << "WEIGHT" << setw(18) << "COST/kg" 
<< setw(14) << "COST" << endl ;

cout << setw(14) << left << item << setw(16) << weight << "kg" << setw(18) << "$" 
<< costperkg << setw(14) << "$" << totalcost << endl << endl ;
}

This one works:

ostringstream streamweight, streamcostperkg, streamtotalcost;
    streamweight << fixed << showpoint << setprecision(2) << weight ;
    streamcostperkg << fixed << showpoint << setprecision(2) << costperkg ;
    streamtotalcost << fixed << showpoint << setprecision(2) << totalcost ;

    string strweight = streamweight.str() + " kg" ; 
    string strcostperkg = "$" + streamcostperkg.str() ;
    string strtotalcost = "$" + streamtotalcost.str() ;


    cout << setw(14) << left << item << setw(16) << strweight << setw(18) << strcostperkg 
<< setw(14) << strtotalcost << endl << endl ;

The expected result is : ITEM WEIGHT COST/kg COST A 2.0 kg $1.98 $3.96 What I got instead is : ITEM WEIGHT COST/kg COST A 2.00 kg$ 1.98$ 3.96

Why does the setw one not work? and also for those viewing on phone, the first character from first and second life of every word should align on the first letter (A, 2, $, $)

1 Answers1

0

OP suspected the std::setw() not to work. IMHO, OP is not aware that the setw() does exactly what's expected but the formatting considers as well the std::left manipulator which makes all following output left aligned. (The left alignment becomes effective in combination with setw() only.)

Example:

#include <iostream>
#include <iomanip>

// the rest of sample
int main()
{
  std::cout << '|' << std::setw(10) << 2.0 << "|kg" << '\n';
  std::cout << std::left << '|' << std::setw(10) << 2.0 << "|kg" << '\n';
  // done
  return 0;
}

Output:

|         2|kg
|2         |kg

Live Demo on coliru

(A possible fix is exposed in the question by OP her/himself.)

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56