Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why extra value is printed using cout and printf?

Why 5 is being printed after 1.00.

#include<iostream>
using namespace std;
int main() {
    double x = 1;
    cout << printf("%.2f\n", x);
    return 0;
}

output :

1.00

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

5

>Solution :

From the C Standard (7.21.6.3 The printf function)

3 The printf function returns the number of characters transmitted, or
a negative value if an output or encoding error occurred.

This call of printf

printf("%.2f\n", x)

outputs on console the following characters (shown as a string)

"1.00\n"

That is 5 characters including the new line character '\n'. The return value of the call is 5 according to the quote of the C Standard. And this value is outputted using the operator << for the standard output C++ stream std::cout.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading