Reputation: 317
I'm trying to change a printf
statement into an std::cout
statement. How would I go about doing that for the following:
printf("\n %.2f Celsius = %.2f Fahrenheit", celsius, fahrenheit);
celcius
and fahrenheit
are both of float
type, and %f
comes from scanf("%f", &fahrenheit);
.
Upvotes: 1
Views: 344
Reputation: 14637
You can use stream manipulators std::fixed
and std::setprecision
from <iomanip>
header to achieve this.
Here's an example:
#include <iostream>
#include <iomanip>
// printf("\n %.2f Celsius = %.2f Fahrenheit", celsius, fahrenheit);
int main()
{
const float celsius = 10.555;
const float fahrenheit = 50.999;
std::cout << '\n'
<< std::fixed
<< std::setprecision( 2 )
<< celsius << " Celsius = "
<< fahrenheit << " Fahrenheit";
return 0;
}
Output:
10.56 Celsius = 51.00 Fahrenheit
Here's the live example: https://ideone.com/ElJ0Wg
But, this is not as compact as it is with printf
. However, there's this formatting library (fmt
) that tries to achieve the compactness of printf
along with other good stuff. And, AFAIK, it has been proposed to be included in the C++ standard library. So, IMO, it would be a good idea to explore and use it in your projects.
Upvotes: 5