简体   繁体   English

将printf更改为cout语句

[英]Changing a printf to a cout statement

I'm trying to change a printf statement into an std::cout statement. 我正在尝试将printf语句更改为std::cout语句。 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); celciusfahrenheit都是float类型, %f来自scanf("%f", &fahrenheit); .

You can use stream manipulators std::fixed and std::setprecision from <iomanip> header to achieve this. 您可以使用<iomanip>标头中的流操纵器 std::fixedstd::setprecision <iomanip>来实现此目的。

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 10.56摄氏度= 51.00华氏度

Here's the live example: https://ideone.com/ElJ0Wg 这是实时示例: https : //ideone.com/ElJ0Wg

But, this is not as compact as it is with printf . 但是,这并不像printf那样紧凑。 However, there's this formatting library ( fmt ) that tries to achieve the compactness of printf along with other good stuff. 但是,有一个格式化库( fmt )试图与其他好的东西一起实现printf的紧凑性。 And, AFAIK, it has been proposed to be included in the C++ standard library. 而且,已经建议将AFAIK包含在C ++标准库中。 So, IMO, it would be a good idea to explore and use it in your projects. 因此,IMO,在您的项目中探索和使用它是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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