简体   繁体   中英

Changing a printf to a cout statement

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); .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM