Dylan L.
Dylan L.

Reputation: 1317

how to set.precision on multiple variables in a single cout

I have this in main:

Product newProduct;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
newProduct.display();

in Product.cpp I have:

cout << "$" << basePrice << " - " 
     << name << " - " << cout.precision(1) << weight << " lbs\n";

but changing the precision to (1) in the .cpp changes the basePrice to (1) as well. How do I change the precision on different variables in the same cout? is there a way? or do I just place them in different cout's? Would that even work? why or why not?

Update when I try the second cout it is adding the number 2 to the end of my name variable. In other words I ended the first cout after the name variable. It is working but adds the number 2 to the end.

Upvotes: 0

Views: 5346

Answers (1)

iksemyonov
iksemyonov

Reputation: 4196

Use the std::setprecision manipulator instead:

cout << setprecision(2) << "$" << basePrice << " - " 
 << name << " - " << setprecision(1) << weight << " lbs\n";

The number 2 is the return value of cout.precision() function, which is the current precision value, that is being inserted into the stream and thus output.

Edit:

Ouch, forgot to add #include <iomanip>.

Edit 2:

For completeness, see this question of mine on why cout.precision() affects the whole stream when called in the middle.

Upvotes: 3

Related Questions